[Tutor] Python Lists
Jonathan Conrad
rahu at gawab.com
Fri Jul 15 21:36:33 CEST 2005
All of the objects in Python are passed by reference: the address
and the type of the object. The immutable types, such as our old
friend the int, are shared by the function and the application,
as well. Assigning to the function variable containing the int
cannot change the int itself, only the address referenced by the
variable...
<after re-reading the post>
>>> class ClassName:
... class_variable = ["apples", ["oranges"]]
... def __init__ (self, var = class_variable [:]):
... self.instance_variable = var
...
>>> oo = ClassName ()
>>> oo.class_variable.append ("fruit flies")
>>> oo.instance_variable.append ("pears")
>>> ov = ClassName ()
>>> ov.instance_variable.append ("tomato")
>>> ov.instance_variable [1].append ("mold")
>>> ow = ClassName ()
>>> oo.instance_variable
["apples", ["oranges"], "pears"]
>>> ov.instance_variable
["apples", ["oranges", "mold"], "fruit flies", "tomato"]
>>> ow.instance_variable
["apples", ["oranges", "mold"], "fruit flies"]
>>>
>>> # Here, we have a comparison of the class_variable to the
... # instance_variable and of a shallow_copy to a deep_copy.
...
... # shallow copy
... x = x [:]
>>> # if x was refering to something else that we do not want
... # changed as we work with it.
>>>
>>> def copylist (*o):
... a = []
... for i in o:
... try: a.append (deep_copy (*i))
... except: a.append (i)
... return a
...
>>> import sys; sys.exit (005)
(For the C/C+ (sic.) types: the dereferentiation operator... *)
More information about the Tutor
mailing list