Python classmethod 修饰符

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

实例:

 1 #!/usr/bin/python
 2 # -*- coding: UTF-8 -*-
 3  
 4 class A(object):
 5     bar = 1
 6     def func1(self):  
 7         print 'foo'  
 8     @classmethod
 9     def func2(cls):
10         print 'func2'
11         print cls.bar
12         cls().func1()   # 调用 foo 方法
13  
14 A.func2()               # 不需要实例化

输出:

1 func2
2 1
3 foo
原文地址:https://www.cnblogs.com/guyuyuan/p/7085933.html