Python面向对象 | 类方法 classmethod
类方法:必须通过类的调用,而且此方法的意义:就是对类里面的变量或者方法进行修改添加。 例一个商店,店庆全场八折,代码怎么写呢? class Goods: __discount = 0.8 # 折扣 def __init__(self,name,origin_price): self.name = name self.__price = origin_price @property def price(self): return self.__price * Goods.__discount apple = Goods('apple',5) banana = Goods('banana',8) print(apple.price) print(banana.price) ''' 执行输出: 4.0 6.4 ''' 现在折扣变了,店庆结束,恢复原价。 如何修改__discount变量呢 ?不能这么写。 Goods._Goods__discount = 1 怎么办呢? 定义一个方法,修改属性 class Goods: __discount = 0.8 def __init__(self,name,origin_price): self.name = name self.__price = origin_price @property def price(self): return