class A(object): bar = 1 def func1(self): print("foo") @classmethod def func2(cls): print("func2") print(cls.bar) cls().func1() A.func2()
@classmethod的作用实际时可以在class内部实例化class。作用就是比u输入的数据需要清晰一遍再实例化,可以把清洗函数定义在class内部并加上@classmethod装饰器已达到减少代码的目的。总结起来就是:@classmethod可以用来为一个类创建一些预处理的实例。
@staticmethod用于修饰类中的方法,使其可以在不创建类实例的情况下调用方法,这样做的好处是执行效率比较高。当然,也可以像一般的方法一样用实例调用该方法。该方法一般称为静态方法,静态方法不可以引用类中的属性或方法,其参数列表也不需要约定的默认参数self。
class Time(object): def __init__(self,sec): self.sec = sec @staticmethod def sec_minutes(s1,s2): return abs(s1-s2) t= Time(10) print(Time.sec_minutes(10,5),t.sec_minutes(t.sec,5))
分别使用类名调用和使用实例调用静态方法,结果为5,5
- staticmethod classmethod 作用 pythonstaticmethod classmethod作用python 矩阵multiply_python staticmethod classmethod staticmethod classmethod python 方法staticmethod静态classmethod staticmethod静态 方法python classmethod decorator python static staticmethod classmehtod property python staticmethod classmethod classmethod函数