python学习之@classmethod @staticmethod

这个答案的原文是Difference between @staticmethod and @classmethod in Python

classmethod 与staticmethod非常类似,区别在于classmethod的第一个参数必须是类对象的引用,而staticmethod可以完全不带参数。

Example:


解释:

当class的定义只是简单如下时:


我们想要解析格式如 11-09-2012类型的日期时,可以如下:


当需要处理的日期量变多时,我们希望对字符串格式日期的处理由类来完成,这样逻辑变得简单。

@classmethod方法可以派上用场,此时它相当于另一个构造函数,同样返回Date实例


好处在于:

1.实现了date字符串在同一个地方解析,而且可重复调用

2.无论调用from_string函数的是实例还是类,第一个参数始终传入的是类本身

@staticmethod 

装饰的函数类似于c++中类的static函数, 只专属于类,与类的实例没有任何关系

第一篇博客,哈哈, 比较丑陋。。。。加油!!


参考:

https://stackoverflow.com/questions/12179271/meaning-of-classmethod-and-staticmethod-for-beginner/12179752

https://www.zhihu.com/question/20021164








猜你喜欢

转载自blog.csdn.net/jiulixiang_88/article/details/80242953