classmethod类方法和staticmethod 方法
学习文章https://www.cnblogs.com/Eva-J/articles/7293890.html
classmethod 类方法 ,
当这个方法的操作涉及静态属性的时候使用 例如操作__discount 就应该适应
下的函数参数为cls
class Goods:
__discount = 0.5#折扣价
def __init__(self,price,name):
self.__price = price
self.name = name
@property
def price(self):
return self.__price * Goods.__discount
#定义一个函数修改
@classmethod
def change_discount(cls,new_discount):
cls.__discount = new_discount
apple = Goods(5,'apple')
print(apple.price)
#修改为新的折扣价格
apple.change_discount(0.8)
print(apple.price)
Goods.change_discount(0.1)
print(apple.price)
static 静态方法:
在完全面向对象的程序中, 和类没有关系也和对象没有关系 相当于在类外面写的方式 (其实写在类里面和外面一样)
下的函数不需要任何参数,cls self 都不需要, 将这个函数伪装成静态方法
class Goods:
@staticmethod
def get_num():
num = input('请输入数量')
print(num)
apple = Goods(5,'apple')
apple.get_num()
#def get_num():
# num = input('请输入数量')
# print(num)
#写在外面一样
静态方法和类方法比较
1.静态方法和类方法都可以通过对象来调用(推荐用类名调用)
2. 类方法有参数cls ;静态方法没有参数,就像函数一样

浙公网安备 33010602011771号