总而言之,有两种类型的变量与类和对象相关联:类变量和实例变量。类变量与类相关联,但实例变量与对象相关联。这是一个例子:
class TestClass:
classVar = 0
def __init__(self):
self.instanceVar = 0
classVar 是与类 TestClass 关联的类变量。instanceVar 是与 TestClass 类型的对象关联的实例变量。
print(TestClass.classVar) # prints 0
instance1 = TestClass() # creates new instance of TestClass
instance2 = TestClass() # creates another new instance of TestClass
instance1 和 instance2 共享 classVar,因为它们都是 TestClass 类型的对象。
print(instance1.classVar) # prints 0
TestClass.classVar = 1
print(instance1.classVar) # prints 1
print(instance2.classVar) # prints 1
但是,它们都有 instanceVar 的副本,因为它是与单个实例相关联的实例变量,而不是类。
print(instance1.instanceVar) # prints 0
print(TestClass.instanceVar) # error! instanceVar is not a class variable
instance1.instanceVar = 1
print(instance1.instanceVar) # prints 1
print(instance2.instanceVar) # prints 0
As Aaron said, if you try to access an instance variable, Python first checks the instance variables of that object, then the class variables of the object's type. Class variables function as default values for instance variables.