@classmethod
修饰符对应的函数不需要实例化就能直接引用,但是该函数的第一个参数必须是表示自身类的cls参数。
举例如下
class DOG(object):
# 类属性
common = "四条腿"
# 实例化方法(必须实例化类之后才能被调用)
def func1(self): # self : 表示实例化类后的地址id
print("黄色身子")
print(self)
# 类方法(不需要实例化类就可以被类本身调用)
@classmethod
def func2(cls): # cls : 表示没用被实例化的类本身
print("狗的特点")
print(cls)
print(cls.common)
cls().func1()
# 不传递传递默认self参数的方法(该方法也是可以直接被类调用的,但是这样做不标准)
def func3():
print("func3")
print(DOG.common) # 属性是可以直接用类本身调用的
DOG.func1() #直接调用会报错,因为该函数调用时需要默认传递实例化类后的地址id参数
输出结果
TypeError Traceback (most recent call last)
<ipython-input-5-44aadef46d36> in <module>()
----> 1 DOG.func1()
TypeError: func1() missing 1 required positional argument: 'self'
DOG.func2() #不需实例化,直接调用
输出结果
狗的特点
<class '__main__.DOG'>
四条腿
黄色身子
<__main__.DOG object at 0x7f6fb63ebba8>
DOG.func3() #也能直接调用,但不推荐这种方法
输出结果
func3
四条腿