Посмотрите, как вы можете сделать это визуально с помощью оператора is (НЕ с ==):
class MyClass(object):
a = [1]
b = 1
def __init__(self):
print(self.a, id(MyClass.a))
print(self.b, id(MyClass.b))
def modify(self):
self.a.append(2)
print("modfied list attribute:", MyClass.a, id(MyClass.a))
print("modfied listattribute:", self.a, id(self.a))
self.b += 1
print("modfied int attribute:", MyClass.b, id(MyClass.b))
print("modfied int attribute:", self.b, id(self.b))
x = MyClass()
y = MyClass()
print(x.a is y.a) # True
print(x.b is y.b) # True
x.modify()
print(x.a is y.a) # True
print(x.b is y.b) # Falseclass MyClass(object):
a = [1]
b = 1
def __init__(self):
print(self.a, id(MyClass.a))
print(self.b, id(MyClass.b))
def modify(self):
self.a.append(2)
print("modfied list attribute:", MyClass.a, id(MyClass.a))
print("modfied listattribute:", self.a, id(self.a))
self.b += 1
print("modfied int attribute:", MyClass.b, id(MyClass.b))
print("modfied int attribute:", self.b, id(self.b))
x = MyClass()
y = MyClass()
# Before changing something a and b is a reference to the same object
print(x.a is y.a) # True
print(x.b is y.b) # True
x.modify()
# After that only x.b is a reference to a new object
# you accessed the list object that is shared and append a value
print(x.a is y.a) # True
print(x.b is y.b) # False
# If you would give x.a a new list it would look like this
x.a = []
print(x.a is y.a) # False
print(x.b is y.b) # False
# x.a is now not the same list as y.a
Если у вас нет причин использовать a и b в качестве атрибута класса, я бы посоветовал вам сделать этоатрибуты экземпляра:
class MyClass(object):
def __init__(self):
self.a = [1]
self.b = 1
print(self.a, id(self.a))
print(self.b, id(self.b))
def modify(self):
self.a.append(2)
print("modfied list attribute:", self.a, id(self.a))
print("modfied listattribute:", self.a, id(self.a))
self.b += 1
print("modfied int attribute:", self.b, id(self.b))
print("modfied int attribute:", self.b, id(self.b))
x = MyClass()
y = MyClass()
print(x.a is y.a) # False
print(x.b is y.b) # False
x.modify()
print(x.a is y.a) # False
print(x.b is y.b) # False
x.a = []
print(x.a is y.a) # False
print(x.b is y.b) # False