5. 类方法

类方法 @classmethod

什么是类方法

类方法是用于描述类的行为的方法,类方法属于类,不属于该类创建的对象。

说明

示例

class Car:
    total_count = 0  # 此类属性用于记录所有车对象的数量。
    def __init__(self, brand, model):
        self.brand, self.model = brand, model
        self.__class__.total_count += 1  # 总数加1
        print(self.brand, self.model, '被创建')

    def __del__(self):
        self.__class__.total_count -= 1  # 总数减1
        print(self.brand, self.model, '被销毁')

    @classmethod
    def get_total_count(cls):
        return cls.total_count


car1 = Car('比亚迪', '秦')
car2 = Car('小米', 'SU7')
print(Car.get_total_count())
del car2
print(car1.get_total_count())

上述程序中, total_count 只有一个,他属于类Car,它的对像可以对其取值,但要对其赋值则必须通过 __class__ 属性进行操作。

get_total_count 是类方法,他需要通过 类 Car 或 Car 类的对象调用,但在方法内只能通过 cls 属性访问类,但不能访问调用此方法的对象。