python-self、cls、classmethod、staticmethod

【简单阐释】

self代表类对象
cls代表类本身

@classmethod 实现类方法-不需要self参数,但第一个参数需要是表示自身类的cls参数。

@classmethod因为持有cls参数(cls 为约定俗成,可更改名称),可以来调用类的属性,类的方法,实例化对象等,避免硬编码(见下图2)
1,类本身
2,类对象

@staticmethod实现静态方法-不需要表示自身对象的self和自身类的cls参数,就跟使用函数一样。

在@staticmethod中要调用到这个类的一些属性方法,只能直接类名.属性名或类名.方法名。
1, 类本身
2,类对象

【代码&图片演示】

class A:
    
    def __init__(self):
        pass
 
    @classmethod
    def print1(cls):
        print ("This is a classmethod")
        
    def print2(self):
        print ("This ia a A instance")
        
    @staticmethod
    def print4():
        print ("This is a staticmethod")

图1:
python-self、cls、classmethod、staticmethod

图2:硬编码简单阐释
python-self、cls、classmethod、staticmethod