class Test01:
arg1 = 'xx'
@staticmethod
def static_fun_self(self): # self只是变量
print('static fun self:', self)
@staticmethod
def static_fun_cls(cls): # cls只是变量
print('static fun cls:', cls)
@classmethod
def set_cls_arg1(cls, arg1):
cls.arg1 = arg1 # 设置类的值
@classmethod
def class_fun(cls):
print('class fun' + cls.arg1)
def fun(self):
print('fun' + self.arg1)
def set_arg1(self, arg1):
self.arg1 = arg1 # 设置实例的值
if __name__ == '__main__':
t1 = Test01()
t1.set_arg1('ss')
t1.set_cls_arg1('sx')
t1.static_fun_cls('cls')
t1.class_fun()
t1.fun()
--------------------------
输出结果1.
t1 = Test01()
t1.set_arg1('ss')
t1.set_cls_arg1('sx')
t1.static_fun_cls('cls')
t1.class_fun()
t1.fun()
----
static fun cls: cls
class funsx
funss
设置cls self的值不同获取的值也不一样
输出结果2.
t1 = Test01()
t1.set_arg1('ss')
# t1.set_cls_arg1('sx')
t1.static_fun_cls('cls')
t1.class_fun()
t1.fun()
----
static fun cls: cls
class funxx
funss
设置self的值 cls获取不到
输出结果3.
t1 = Test01()
# t1.set_arg1('ss')
t1.set_cls_arg1('sx')
t1.static_fun_cls('cls')
t1.class_fun()
t1.fun()
----
static fun cls: cls
class funsx
funsx
设置 cls的值 self, cls都可以获取到
输出结果4.
t1 = Test01()
# t1.set_arg1('ss')
# t1.set_cls_arg1('sx')
t1.static_fun_cls('cls')
t1.class_fun()
t1.fun()
static fun cls: cls
class funxx
funxx
---------------------------
通过@staticmethod修饰的函数在类中获取不到self,cls, 相当于一个普通函数
通过@classmethod修饰的函数可以通过cls.变量名 改变类中变量的值其他函数的值也更改
instance函数可以通过self.变量名 改变调用者变量的值,其他函数的值不更改