小编mic*_*err的帖子

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

假设我们在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递增,但没有奏效.

python oop class-method

11
推荐指数
1
解决办法
306
查看次数

标签 统计

class-method ×1

oop ×1

python ×1