Newbie: question regarding references and class relationships
Rui Maciel
rui.maciel at gmail.com
Mon Jun 10 10:38:20 EDT 2013
Peter Otten wrote:
> Rui Maciel wrote:
>
>> Peter Otten wrote:
>>
>>> Don't add
>>>
>>>>position = []
>>>
>>> to your code. That's not a declaration, but a class attribute and in the
>>> long run it will cause nothing but trouble.
>>
>> Why's that?
>
> Especially with mutable attributes it's hard to keep track whether you are
> operating on the instance or the class:
>
>>>> class Point:
> ... position = []
> ... def __init__(self, x, y, z):
> ... self.position = [x, y, z]
> ...
>>>> a = Point(1, 2, 3)
>>>> b = Point(10, 20, 30)
>>>> a.position
> [1, 2, 3]
>>>> del a.position
>>>> a.position
> [] # did you expect that?
>>>> del b.position
>>>> b.position.extend(["did you expect that?"])
>>>> a.position
> ['did you expect that?']
>>>> del a.position
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> AttributeError: position
How do you guarantee that any object of a class has a specific set of
attributes?
Rui Maciel
More information about the Python-list
mailing list