@classmethod方法介绍
文章目录
前言
classmethod是用来指定一个类的方法为类方法,没有此参数指定的类的方法为实例方法,说人话无需类实列化调用类中函数或方法的关键字
一、格式
必须使用关键字@classmethod且函数第一个参数必须cls(类似self),如下:
class C: @classmethod def f(cls, 参数1, 参数2, ...): ... 二、使用应用
我比较粗暴,直接上列子,如下代码:
class A(): d = 60 def __init__(self,n): # 构造函数里的属性 self.n=n self.b=self.rand_b() self.c=60 def rand_b(self): import random return random.random() def dd(self): print('dd') @classmethod def cls_print(cls): # 已经尝试无法调用构造函数里的属性(如:cls.c/cls.n/cls.b),除非利用实列调用; # 但能调用以外属性,如cls.d与self.d含义一致,但由于不是self,不能写成self.d调用; print(cls) # cls.dd() 这种使用是错误的,不能使用 print(cls.d+2) return cls.d+2 def g(self): # 这里self.cls_print()使用self调用,因其本身就是类方法,故用self. k = self.cls_print()+self.d print('g function:', k) if __name__ == '__main__': # 可直接使用下面调用 A.cls_print() # 将类方法使用普通类调用,相当于cls变成cls,和普通类方法调用一样 B = A(6) B.cls_print() B.g() 1、类方法说明
我使用cls_print(cls)为类函数,把它当作一般函数多了一个必须的cls参数作为第一位,你可以使用cls中的参数,
如cls.d,但不能使用构造函数属性也不能调用其它方法,如cls.dd(),其它就和普通函数差不多,如下:
class A(): d = 60 @classmethod def cls_print(cls): # 已经尝试无法调用构造函数里的属性(如:cls.c/cls.n/cls.b),除非利用实列调用; # 但能调用以外属性,如cls.d与self.d含义一致,但由于不是self,不能写成self.d调用; print(cls) # cls.dd() 这种使用是错误的,不能使用 print(cls.d+2) return cls.d+2 2、类方法应用
简单说直接使用A.类方法就可调用,根本不用构造类实列,也不用管类的构造函数,如下代码:
if __name__ == '__main__': # 可直接使用下面调用 A.cls_print() 3、类方法作为普通函数应用
不想解释,就是一句话,使用类的实列,就当作普通函数调用。
if __name__ == '__main__': # 将类方法使用普通类调用,相当于cls变成cls,和普通类方法调用一样 B = A(6) B.cls_print() B.g()