23 面向对象6:类的方法
class Animal(object): count = 0 @classmethod #定义类方法,上一行 def show_count(cls): #定义类方法 cls强制必须,指代Animal类 print("Animal count: %d"%cls.count) #使用cls. 引用count属性 def __init__(self,name): #定义对象初始化方法 self.name=name Animal.count+=1 dog=Animal("dog") #类实例化 cat=Animal("cat") Animal.show_count() 调用类方法
运行结果:
Animal count: 2