Class Variable Access and Assignment
Antoon Pardon
apardon at forel.vub.ac.be
Fri Nov 4 10:10:17 EST 2005
Op 2005-11-04, Christopher Subich schreef <csubich.spam.block at spam.subich.block.com>:
> Antoon Pardon wrote:
>> Op 2005-11-03, Stefan Arentz schreef <stefan.arentz at gmail.com>:
>>>The model makes sense in my opinion. If you don't like it then there are
>>>plenty of other languages to choose from that have decided to implement
>>>things differently.
>>
> >>> class foo:
> >>> x = [5]
> >>> a = foo()
> >>> a += [6]
> >>> a.x
> [5,6]
> >>> foo.x
> [5,6]
> >>> foo.x = [7]
> >>> a.x
> [5,6]
>
> In truth, this all does make perfect sense -- if you consider class
> variables mostly good for "setting defaults" on instances.
Except when your default is a list
class foo:
x = [] # default
a = foo()
a.x += [3]
b = foo()
b.x
This results in [3]. So in this case using a class variable x to
provide a default empty list doesn't work out in combination
with augmented operators.
This however would work:
class foo:
x = [] # default
a = foo()
a.x = a.x + [3]
b = foo()
b.x
This results in []
--
Antoon Pardon
More information about the Python-list
mailing list