假设我们在Python中有一个Pet类:
class Pet(object):
num_pets = 0
def __init__(self, name):
self.name = name
Pet.num_pets += 1
def speak(self):
print("My name's %s and the number of pets is %d" % (self.name, self.num_pets))
Run Code Online (Sandbox Code Playgroud)
我希望init方法创建一个实例,但也要更新类的属性.有没有比上面的代码更优雅的方式来做到这一点?我试图传递self和cls到init方法,然后参照CLS,而不是宠物,其中num_pets递增,但没有奏效.