[Tutor] initializing multiple attributes to same value
dman
dsh8290@rit.edu
Fri, 21 Dec 2001 13:08:26 -0500
On Thu, Dec 20, 2001 at 12:14:53AM -0600, Rob McGee wrote:
| I tripped myself up on something like this:
|
| {code}
| class Whatever:
| def __init__(self):
| self.one = self.two = self.three = 0
This works as intended because integers are immutable.
| self.listOne = self.listTwo = []
If you then try
self.listOne.append( "foo" )
you'll see that both names refer to the same object, and you just
changed that object.
| def __init__(self):
| list1 = self.one, self.two, self.three
| for item in list1:
| item = 0
| list2 = self.listOne, self.listTwo
| for item in list2:
| item = []
This won't work because you are assigning to the name 'item', not
'self.listOne'. Also, 'self.listOne' must exist before you can put it
in a tuple.
-D
--
"GUIs normally make it simple to accomplish simple actions and
impossible to accomplish complex actions."
--Doug Gwyn (22/Jun/91 in comp.unix.wizards)