Python 中的 @staticmethod和@classmethod(关键词:Python/静态方法/类方法/@staticmethod/@classmethod)

版权声明:本文为博主原创文章,可以转载,但转载前请联系博主。 https://blog.csdn.net/qq_33528613/article/details/84348437

结合书籍,我的理解
静态方法: 出现在类中,第 1 个参数不是实例、也不是类, 由 @staticmethod 装饰的方法;
类方法: 出现在类中,第 1 个参数不是实例、而是类, 由 @classmethod 装饰的方法。

class C:
        @staticmethod
        def smeth(x):
                print(x)

        @classmethod
        def cmeth(cls, x):
                print(cls, x)

输出:

>>> c1 = C()
>>> c1.smeth(1)
1
>>> C.smeth(2)
2
>>> c1.cmeth(1)
<class 'q.C'> 1
>>> C.cmeth(1)
<class 'q.C'> 1

参考文献:

  1. 《Python 学习手册(第 4 版)》 - ;
  2. 3 @staticmethod和@classmethod

猜你喜欢

转载自blog.csdn.net/qq_33528613/article/details/84348437