类变量在类的所有实例之间共享.对于不可变类型(如int,str,…),你不会注意到很多不同之处.但考虑一下:
class MyClass():
temp = []
def myfunc(self, val):
self.temp.append(val)
print self.temp
instance1 = MyClass()
instance1.myfunc(1) # [1]
instance2 = MyClass()
instance2.myfunc(2) # [1, 2]
在这种情况下,两个实例共享相同的列表,即如果实例本身没有临时成员,则使用该类的实例.
所以,如果你进一步做:
MyClass.temp.append(3)
print instance1.temp # [1, 2, 3]
instance1.temp = []
print instance1.temp # [] uses the instances temp
print instance2.temp # [1, 2, 3]
del instance1.temp
print instance1.temp # [1, 2, 3] uses the class' temp again