class cls():
A = []
a = cls()
b = cls()
a.A.append("a")
print(b.A)
I run this on python 3.4. but i see it print a stting "a".
I cant understand why this happen. a is different from b, but why they are share one var A?
class cls():
A = []
a = cls()
b = cls()
a.A.append("a")
print(b.A)
I run this on python 3.4. but i see it print a stting "a".
I cant understand why this happen. a is different from b, but why they are share one var A?
You've assigned a variable to the class. It only exists once for all instances (as long as you use it by reference, which .append
does).
What you really want is an instance variable:
class cls():
def __init__(self):
self.A = []
a = cls()
b = cls()
a.A.append("a")
print(b.A)
Also, cls
should not be used as the name of a class - use CamelCase
names, and additionally cls
should only be used with metaclasses or classmethods (you are unlikely to need either of these).