9.3.5. 类和实例变量

一般来说,实例变量用于每个实例的唯一数据,而类变量用于类的所有实例共享的属性和方法:

  1. class Dog:
  2. kind = 'canine' # class variable shared by all instances
  3. def __init__(self, name):
  4. self.name = name # instance variable unique to each instance
  5. >>> d = Dog('Fido')
  6. >>> e = Dog('Buddy')
  7. >>> d.kind # shared by all dogs
  8. 'canine'
  9. >>> e.kind # shared by all dogs
  10. 'canine'
  11. >>> d.name # unique to d
  12. 'Fido'
  13. >>> e.name # unique to e
  14. 'Buddy'

正如 名称和对象 中已讨论过的,共享数据可能在涉及 mutable 对象例如列表和字典的时候导致令人惊讶的结果。 例如以下代码中的 tricks 列表不应该被用作类变量,因为所有的 Dog 实例将只共享一个单独的列表:

  1. class Dog:
  2. tricks = [] # mistaken use of a class variable
  3. def __init__(self, name):
  4. self.name = name
  5. def add_trick(self, trick):
  6. self.tricks.append(trick)
  7. >>> d = Dog('Fido')
  8. >>> e = Dog('Buddy')
  9. >>> d.add_trick('roll over')
  10. >>> e.add_trick('play dead')
  11. >>> d.tricks # unexpectedly shared by all dogs
  12. ['roll over', 'play dead']

正确的类设计应该使用实例变量:

  1. class Dog:
  2. def __init__(self, name):
  3. self.name = name
  4. self.tricks = [] # creates a new empty list for each dog
  5. def add_trick(self, trick):
  6. self.tricks.append(trick)
  7. >>> d = Dog('Fido')
  8. >>> e = Dog('Buddy')
  9. >>> d.add_trick('roll over')
  10. >>> e.add_trick('play dead')
  11. >>> d.tricks
  12. ['roll over']
  13. >>> e.tricks
  14. ['play dead']