为什么我的__init__函数需要是@classmethod?
这是我写的一个测试代码片段。我发现如果我不把初始化方法定义为类方法,代码就无法运行:
class A(object):
def __init__(self):
self.value = 0
self.add(1)
@classmethod
def add(self, arg):
self.value += arg
class B(A):
@classmethod
def add(self, arg):
self.value += arg * 2
if __name__ == '__main__':
a = A()
b = B()
print a.value
print b.value
这段代码的输出是:
Traceback (most recent call last):
File "inherit.py", line 17, in <module>
a = A()
File "inherit.py", line 4, in __init__
self.add(1)
File "inherit.py", line 8, in add
self.value += arg
AttributeError: type object 'A' has no attribute 'value'
但是如果我把我的初始化函数改成 @classmethod
,代码就能正常工作了:
class A(object):
@classmethod
def __init__(self):
self.value = 0
self.add(1)
@classmethod
def add(self, arg):
self.value += arg
class B(A):
@classmethod
def add(self, arg):
self.value += arg * 2
if __name__ == '__main__':
a = A()
b = B()
print a.value
print b.value
输出结果是:
1
2
我原以为初始化方法默认就是一个类方法,并且第一个参数应该是 self。到底发生了什么呢?
1 个回答
5
问题在于你把 add
函数标记成了 classmethod
,但实际上它并不是。把 add
前面的 @classmethod
去掉,应该就能正常工作了。