staticmethod 只能作为函数装饰器应用。其作用为将一个函数转换为静态方法。下面一段代码中,若不在def get(argv1)上添加装饰器staticmethod.
在执行代码test.get("hello")  将会出现 TypeError: get() takes 1 positional argument but 2 were given。
这说明 在不添加装饰器staticmethod,Python 解释器仅仅将def get(argv1) 解释为类C 内部定义的函数;添加后,则将其解释为类C 的静态方法。
class C:
    def __init__(self):
        self._item = 1
    
    @staticmethod
    def get(argv1):
        # print(self._item)
        print(argv1)
test = C()
test.get(‘hello‘)
C.get(‘hello‘)
classmethod,与staticmethod类似, 只能作为函数装饰器应用。其作用为将一个函数转换为类方法。若不在def get(argv1)上添加装饰器classmethod.
在执行代码时 C.get(‘hello‘)将会出现 TypeError: get() missing 1 required positional argument: ‘argv1‘ 。
这说明 在不添加装饰器classmethod,Python 解释器不会讲C作为cls 传输给 get(cls,argv) 。
class C:
    def __init__(self):
        self._item = 1
   
    @classmethod
    def get(cls, argv1):
        # print(self._item)
        print(argv1)
test = C()
test.get(‘hello‘)
C.get(‘hello‘)
| staticmethod | classmethod | |
|---|---|---|
| 区别 | 讲func 装换为静态方法 | 将func 转换为类方法 | 
| 相似点 | 调用方式相同 | 
python内置装饰器---- staticmethod和classmethod
原文:https://www.cnblogs.com/Finding-bugs/p/14178436.html