date: 2021-11-09title: classmethod和staticmethod装饰器 #标题
tags: #标签
categories: python # 分类
这里记录下classmethod和staticmethod这两个装饰器,参考:老男孩教育。
classmethod
这个装饰器使用场景比较多。
# 未使用classmethod装饰器class Goods:__discount=0.8def __init__(self):self.__price=5self.price=self.__price * Goods.__discountdef change_discount(self,new_price):Goods.__discount=new_priceG=Goods()print(G.price) # 4.0G.change_discount(0.4)H=Goods()print(H.price) # 2.0# 使用classmethod装饰器class Goods:__discount = 0.8def __init__(self):self.__price = 5self.price = self.__price * Goods.__discount@classmethod # 把一个对象绑定的方法,修改成一个 类方法# 也就是说,被classmethod装饰的方法会成为一个类方法def change_discount(cls, new_price): # 将原有的self更改为cls,表示当前Goods类cls.__discount = new_priceG = Goods()print(G.price) # 4.0Goods.change_discount(0.4) # 当使用classmethod装饰器后,我们就可以通过类名在外部调用这个方法# 也不用实例化对象,就直接用类名在外部调用这个方法H = Goods()print(H.price) # 2.0'''什么时候用classmethod?1、定义了一个方法,默认传self,但这个self没有被使用;2、并且你在这个方法里用到了当前的类名,或者你准备使用这个类的内存空间中的名字的时候。'''
staticmethod
这个装饰器用的比较少,只要你的team没有严格要求必须面向对象编程,那你就踏踏实实的在外部直接定义函数即可。
class User:pass@staticmethod # 当一个普通函数被挪到类的内部执行,那么直接加@staticmethod这个装饰器即可,def func(a, b):print(a, b)# 可以通过实例化后的方式进行调用obj = User()obj.func(1, 2)# 也可以直接通过类名去调用User.func(3, 4)
