这是我作为测试编写的代码段。我注意到如果我没有将init方法定义为类方法,则代码不会运行:
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'
但是,如果我将init函数更改为@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
我的印象是init默认情况下是一个类方法,其第一个参数必须是self。发生了什么事?
答案 0 :(得分:4)
问题是您add
标记为classmethod
,但它不是。从@classmethod
中取出add
,它应该有效。