[Tutor] initializing multiple attributes to same value
Andy W
toodles@yifan.net
Thu, 20 Dec 2001 14:33:43 +0800
Hiya,
(Answer is right down the bottom)
> I tripped myself up on something like this:
>
> {code}
> class Whatever:
> def __init__(self):
> self.one = self.two = self.three = 0
> self.listOne = self.listTwo = []
>
> whoKnows = Whatever()
>
> someOtherObject = ['spam', 'eggs']
>
> whoKnows.listOne.append(someOtherObject)
> {/code}
>
> With that I also end up with someOtherObject in whoKnows.listTwo.
> Presumably if I add 42 to whoKnows.one, I also add 42 to the values for
> two and three attributes. Is that right?
>
> So, how do I initialize multiple attributes to the same value? Would
> something like this ...
>
> {code}
> class Whatever:
> 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 = []
> {/code}
>
> ... keep these attributes' values distinct from one another?
Well, no. That would be referring to variables not yet assigned. You could
use a dictionary if you wanted to do it that way, with the keys as "one",
"two", "three" etc.
Another way is to use sequence unpacking, eg.:-
self.one, self.two, self.three = (0,0,0)
HTH,
Andrew
>
> Thanks,
> Rob - /dev/rob0
>
> _______________________________________________
> Tutor maillist - Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>