date: 2021-11-09title: classmethod和staticmethod装饰器 #标题
tags: #标签
categories: python # 分类

这里记录下classmethodstaticmethod这两个装饰器,参考:老男孩教育

classmethod

这个装饰器使用场景比较多。

  1. # 未使用classmethod装饰器
  2. class Goods:
  3. __discount=0.8
  4. def __init__(self):
  5. self.__price=5
  6. self.price=self.__price * Goods.__discount
  7. def change_discount(self,new_price):
  8. Goods.__discount=new_price
  9. G=Goods()
  10. print(G.price) # 4.0
  11. G.change_discount(0.4)
  12. H=Goods()
  13. print(H.price) # 2.0
  14. # 使用classmethod装饰器
  15. class Goods:
  16. __discount = 0.8
  17. def __init__(self):
  18. self.__price = 5
  19. self.price = self.__price * Goods.__discount
  20. @classmethod # 把一个对象绑定的方法,修改成一个 类方法
  21. # 也就是说,被classmethod装饰的方法会成为一个类方法
  22. def change_discount(cls, new_price): # 将原有的self更改为cls,表示当前Goods类
  23. cls.__discount = new_price
  24. G = Goods()
  25. print(G.price) # 4.0
  26. Goods.change_discount(0.4) # 当使用classmethod装饰器后,我们就可以通过类名在外部调用这个方法
  27. # 也不用实例化对象,就直接用类名在外部调用这个方法
  28. H = Goods()
  29. print(H.price) # 2.0
  30. '''
  31. 什么时候用classmethod?
  32. 1、定义了一个方法,默认传self,但这个self没有被使用;
  33. 2、并且你在这个方法里用到了当前的类名,或者你准备使用这个类的内存空间中的名字的时候。
  34. '''

staticmethod

这个装饰器用的比较少,只要你的team没有严格要求必须面向对象编程,那你就踏踏实实的在外部直接定义函数即可。

  1. class User:
  2. pass
  3. @staticmethod # 当一个普通函数被挪到类的内部执行,那么直接加@staticmethod这个装饰器即可,
  4. def func(a, b):
  5. print(a, b)
  6. # 可以通过实例化后的方式进行调用
  7. obj = User()
  8. obj.func(1, 2)
  9. # 也可以直接通过类名去调用
  10. User.func(3, 4)