python类方法、静态方法

桃扇骨 2022-01-10 10:59 536阅读 0赞

类方法、静态方法:br/>静态方法定义:
@staticmethod修饰
参数不用self
br/>静态方法特性:
不能引用或访问实例属性
可以通过类.类变量访问类属性
静态方法调用:
可以用类、类实例调用
静态方法本质:
在类中的一个普通函数
使面向对象程序中函数归属于类,易于代码管理
静态方法的用法:
与类相关,但不依赖或改变类与实例
创建不同的实例
把类相关工具方法放入类中
类方法:
定义方法:
@classmethod
必须提供参数cls
访问特性:
不能引用或访问实例属性
调用方法:
可以用类、类实例调用
继承特性:
继承时,传入的变量cls是子类,而非父类
用途:
与类相关,但不依赖或改变类的实例
工厂方法,创建类实例,完成有关预处理
在类内调用静态方法时不用硬编码类名

  1. # -*- coding=utf-8 -*-
  2. class Washer:
  3. company = "Le xi"
  4. def __init__(self,water=10,scour=2):
  5. self._water = water
  6. self.scour = scour
  7. self.year = 2010
  8. pass
  9. @staticmethod
  10. def spins_ml(spins):
  11. print("company:",Washer.company)
  12. return spins * 0.4
  13. @classmethod
  14. def get_washer(cls,water,scour):
  15. return cls(water,Washer.spins_ml(scour))
  16. @property
  17. def water(self):
  18. return self._water
  19. @water.setter
  20. def water(self,water):
  21. if 0 <= water <= 500:
  22. self._water = water
  23. pass
  24. else:
  25. print("输入的值有误!")
  26. pass
  27. pass
  28. @property
  29. def total_year(self):
  30. return 2015-self.year
  31. def set_water(self,water):
  32. self.water = water
  33. pass
  34. def set_scour(self,scour):
  35. self.scour = scour
  36. pass
  37. def add_water(self):
  38. print('Add water:',self.water)
  39. pass
  40. def add_scour(self):
  41. print('Add scour:',self.scour)
  42. pass
  43. def start_wash(self):
  44. self.add_water()
  45. self.add_scour()
  46. print('Start wash...')
  47. pass
  48. pass
  49. if __name__ == '__main__':
  50. print(Washer.spins_ml(8))
  51. w = Washer()
  52. print(w.spins_ml(8))
  53. w = Washer(200,Washer.spins_ml(9))
  54. w.start_wash()
  55. w = Washer.get_washer(200, 10)
  56. w.start_wash()

转载于:https://blog.51cto.com/3945465/2340826

发表评论

表情:
评论列表 (有 0 条评论,536人围观)

还没有评论,来说两句吧...

相关阅读