Python classmethod 修饰符

描述

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

语法

classmethod 语法:

@classmethod

def xxx():

参数

  • 无。

返回值

返回函数的类方法。

实例

以下实例展示了 classmethod 的使用方法:

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

输出:

func2
1
foo

猜你喜欢

转载自www.cnblogs.com/TwCsLj/p/10425665.html