编写一个引用实例和类的python方法

mic*_*err 11 python oop class-method

假设我们在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方法创建一个实例,但也要更新类的属性.有没有比上面的代码更优雅的方式来做到这一点?我试图传递selfcls到init方法,然后参照CLS,而不是宠物,其中num_pets递增,但没有奏效.

mgi*_*son 13

您可以使用a classmethod来增加宠物的数量:

class Pet(object):
    num_pets = 0

    def __init__(self, name):
        self.name = name
        self.incr_num_pets()

    @classmethod
    def incr_num_pets(cls):
        cls.num_pets += 1
Run Code Online (Sandbox Code Playgroud)

另外,还可以增加num_petstype(self):

def __init__(self, name):
    self.name = name
    type(self).num_pets += 1
Run Code Online (Sandbox Code Playgroud)

虽然我发现第二种方法虽然打字较少,但稍微不那么优雅.