在下面的示例中,Test类有两个实例方法和一个类方法。
在set_cls_var_1方法中,我使用self设置了类变量。
在set_cls_var_2方法中,我使用self调用了类方法。
我的问题是:为什么只有classmethod可以由self调用,而类变量不行?
在set_cls_var_1方法中,我使用self设置了类变量。
在set_cls_var_2方法中,我使用self调用了类方法。
class Test():
#class variable
cls_var = 10
def __init__(self):
obj_var=20
def set_cls_var_1(self,val):
#second method to access class variable
print "first "
self.cls_var = val
def set_cls_var_2(self):
print "second"
self.task(200)
@classmethod
def task(cls,val):
cls.cls_var = val
t=Test()
#set class variable by first method
t.set_cls_var_1(100)
print Test.cls_var
#set class variable by second method
t.set_cls_var_2()
print Test.cls_var
输出
first
10
second
200
预期输出
first
100
second
200
我的问题是:为什么只有classmethod可以由self调用,而类变量不行?