03类变量

62 阅读1分钟
class ICBC:
    total_money = 5000  # 类变量  访问时用类名+变量名  例如ICBC.total_money

    def __init__(self, name, money):
        self.name = name
        self.money = money
        ICBC.total_money -= ICBC.total_money - self.money

类变量存在于方法区

类变量定义在类中 方法外

调用:类名.变量名 不建议通过对象访问类变量

image.png image.png

类方法:

class ICBC:
    total_money = 5000  # 类变量  访问时用类名+变量名  例如ICBC.total_money
    @classmethod
    def print_money(cls):
        print(cls.total_money)

cls 与ICBC 一模一样

image.png

image.png