比方说,我们有Python中的宠物类:写引用实例和类都蟒蛇方法
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))
我想INIT方法来创建一个实例,同时也更新属性在课堂上。有没有比上面的代码更优雅的方式来做到这一点?我尝试将self
和cls
传递给init方法,然后引用cls而不是Pet,其中num_pets递增,但那不起作用。
我看到上面的代码足够优雅。除非'num_pets'是一个按类进行管理的属性。我没有看到任何明显的原因,为什么要考虑在这里使用类方法的需要。 – direprobs