经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » Python3 » 查看文章
关于Python3 类方法、静态方法新解
来源:jb51  时间:2019/8/30 11:46:31  对本文有异议

如下所示:

  1. class Date:
  2. def __init__(self, year, month, day):
  3. self.year = year
  4. self.month = month
  5. self.day = day
  6.  
  7. # 实例方法
  8. def tomorrow(self):
  9. self.day +=1
  10.  
  11. def __str__(self):
  12. return '{}/{}/{}'.format(self.year,self.month,self.day)
  13.  
  14. # 静态方法
  15. @staticmethod
  16. def format_date_str(date_str):
  17. year, month, day = tuple(date_str.split('-'))
  18. return Date(int(year),int(month),int(day))
  19.  
  20. # 类方法
  21. # 这里的 cls 实际就是类本身,它将自己本身返回,不需要我们写返回的类名,更好一些
  22. @classmethod
  23. def format_str(cls, date_str):
  24. year, month, day = tuple(date_str.split('-'))
  25. return cls(int(year),int(month),int(day))
  26.  
  27. if __name__ == "__main__":
  28. new = Date(2018,12,12)
  29. print(new)
  30. new.tomorrow()
  31. print(new)
  32.  
  33. # 现在我们想输入一个日期字符串需要怎么做呢?
  34. date_str = '2018-12-30'
  35. year, month, day = tuple(date_str.split('-')) # 这里利用了tuple的拆包属性,将分开的列表分别赋给变量
  36. new = Date(year,month,day)
  37. print(new)
  38. # 如果有静态方法,就会更加简单了
  39. new = Date.format_date_str('2019-12-01')
  40. print(new)
  41. # 但是静态方法还要将类的名称返回,那有没有更好的方法呢
  42. # 那就是类方法,类方法的原理就是 将输入的参数处理后 通过类方法返回一个实例对像,静态方法也是如此,但静态方法可以不返回实例 而返回其他的
  43. new = Date.format_str('2019-9-01')
  44. print(new)
  45. # 那么问题来了?什么使用用静态方法,什么时候使用类方法呢?
  46. # 原则上是:当需要返回实例时使用类方法,不需要返回实例对象时 直接使用静态方法就好了,
  47. # 例如我们做验证日期字符串是否合法的时候没必要返回实例,那就使用 静态方法就可以了

以上这篇关于Python3 类方法、静态方法新解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持w3xue。

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号