This plagued me for hours, as I am from the C++ world. I finally found out what was going on, but I do not know why this is the default behaviour. I'd like to understand why the language is designed this way.
I wanted an instance variable mem
. So I tried this:
class x(object):
mem = []
obj = x()
obj.mem.append(1)
print(obj.mem)
objTWO = x()
objTWO.mem.append(2)
print(objTWO.mem)
Which prints this:
[1]
[1, 2]
Whereas:
class x(object):
def __init__(self):
self.mem = []
obj = x()
obj.mem.append(1)
print(obj.mem)
objTWO = x()
objTWO.mem.append(2)
print(objTWO.mem)
prints
[1]
[2]
Why would the first be the default behaviour? What is the intuition here, since its the opposite of how many mainstream OO languages work (they introduce the static
keyword for the top case, which makes you explicitly say you want a static variable)? To newcomers to Python, this is a surprise.
Also, it seems you are allowed to have an instance variable and a class variable with the same name:
class x(object):
mem = []
def __init__(self):
self.mem = []
I would have to run this to figure out what would be printed. I can't even guess!
class ...:
, the fields are class variables. Only inside an instance initializer does it make sense to declare instance variables. Sure, it's not the C++/Java way of thinking, but it's perfectly understandable. – Ted Hopp Nov 14 '12 at 18:46