Newbie: question regarding references and class relationships

Peter Otten __peter__ at web.de
Mon Jun 10 10:28:30 EDT 2013


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





More information about the Python-list mailing list