osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[Tutor] beginning to code


Bill <BILL_NOSPAM at whoknows.net>:

> I figure that, internally, an address, a pointer, is being passed by
> value to implement pass by reference. Why do you say "they are right"
> above? Are you saying it's not pass by reference?

"Pass by reference" could be "pass by reference to object" (Python,
Java, JavaScript, Lisp) or "pass by reference to memory slot" (available
to Pascal and C++).

Memory slots (or lvalues, as they are known in C) are not first class
objects in Python, which makes "pass by reference to memory slot" a bit
tricky in Python. Python *could* add memory slots to its sanctioned
collection of object types, and it *could* add special syntax to express
a memory slot reference and dereference ("&" and "*" in C).

However, Python doesn't need any language changes to implement memory
slots. A memory slot could be defined as any object that implements
"get()" and "set(value)" methods:

   C: &x

   Python:
      class Xref:
          def get(self): return x
          def set(self, value): nonlocal x; x = value
      ref_x = Xref()


   C: &x->y[3]

   Python:
      class XY3ref:
          def get(self): return x.y[3]
          def set(self, value): x.y[3] = value
      ref_xy3 = XY3ref()

The examples could be simplified:

      ref_x = slot_ref(locals(), "x")
      ref_xy3 = slot_ref(x.y, 3)

by defining:

   def slot_ref(dict_or_array, key_or_index):
       class SlotRef:
           def get(self): return dict_or_array[key_or_index]
           def set(self, value): dict_or_array[key_or_index] = value
       return SlotRef()


Marko