Here is a code:
>>> class A(object):
... value = []
... def method(self, new_value):
... self.value.append(new_value)
...
>>> a = A()
>>> a.value
[]
>>> a.method(1)
>>> b = A()
>>> b.value
[1]
>>> b.method(2)
>>> b.value
[1, 2]
>>> a.value
[1, 2]
This happens only with lists. Is the only way to deffine value in __init__?
How to normally define default class values in python?
UPD
thank you for your responses
>>> class B(object):
... value = "str"
... def method(self):
... self.value += "1"
...
>>> a = B()
>>> a.value
'str'
>>> a.method()
>>> a.value
'str1'
>>> b = B()
>>> b.value
'str'
I don’t get, why list is shared but str is not?
The
valueyou are defining is not an instance field for your class, its more like a static field. But python doesn’t mind if you access this field from instances. So, even if you access this field from instances, it is not a different list for each instance. Basically, you are appending to the same list every time the method is called.You’ll have to do this
Now you have a different list created for each instance.
EDIT: Let me try to explain what happens when you use a
str.That last line in the previous code is the same as this:
Now, this makes it abit easier to see what’s going on. First, python gets the
value from
self.value. Since there is no instance field defined yet onself,this will give
'str'. Add'1'to that and sets it to the instance fieldcalled
value. This is likewhich is the same as you’d set an instance field in the
__init__method (in myfirst snippet of code).
Does that make it clear?