python中@classmethod @staticmethod区别

python staticmethod 返回函数的静态方法。

该方法不强制要求传递参数,如下声明一个静态方法:

class C(object):
    @staticmethod
    def f(arg1, arg2, ...):
        ...

以上实例声明了静态方法 f,类可以不用实例化就可以调用该方法 C.f(),当然也可以实例化后调用 C().f()。

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
class A(object):
    bar = 1
    def func1(self):  
        print ('foo') 
    @classmethod
    def func2(cls):
        print ('func2')
        print (cls.bar)
        cls().func1()   # 调用 foo 方法
 
A.func2()               # 不需要实例化

输出结果为:

func2
1
foo

修饰符对应的函数不需要实例化,不需要 self 参数,但第一个参数需要是表示自身类的 cls 参数,可以来调用类的属性,类的方法,实例化对象等。

原文地址:https://www.cnblogs.com/zhmiao/p/10551654.html