python:@classmethod

python提供了@classmethod和@staticmethod来定义静态方法

1、实例方法,该实例属于对象,该方法的第一个参数是当前实例,拥有当前类以及实例的所有特性。

2、@classmethod 类方法,该实例属于类,该方法的第一个参数是当前类,可以对类做一些处理,如果一个静态方法和类有关但是和实例无关,那么使用该方法。

3、@staticmethod静态方法,该实例属于类,但该方法没有参数,也就是说该方法不能对类做处理,相当于全局方法。

class A(object):
    bar = 1

    def func1(self):
        print('foo')

    @classmethod
    def func2(cls):
        print('func2')
        print(cls.bar)
        print(A.bar)
        cls().func1()
        A().func1() 

输出结果:

func2
1
1
foo
foo

参考文章链接:https://www.cnblogs.com/wyongbo/p/python_static_method.html

https://www.runoob.com/python/python-func-classmethod.html

python : @classmethod 的一个使用场合:https://blog.csdn.net/dyh4201/article/details/78336529

 

你可能感兴趣的:(python)