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

 

相关文章:

  • 2021-06-22
  • 2022-12-23
  • 2022-12-23
  • 2022-01-08
  • 2022-02-13
  • 2021-08-26
  • 2021-07-02
猜你喜欢
  • 2022-12-23
  • 2021-12-28
  • 2022-12-23
  • 2021-06-10
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案