K E*_*gle 1 python inheritance
这是我作为测试编写的代码片段。我注意到,如果我不将 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
Run Code Online (Sandbox Code Playgroud)
这输出:
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'
Run Code Online (Sandbox Code Playgroud)
但是,如果我将 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
Run Code Online (Sandbox Code Playgroud)
输出:
1
2
Run Code Online (Sandbox Code Playgroud)
我的印象是 init 默认是一个类方法,其第一个参数必须是 self。到底是怎么回事?
问题是您已add标记为 a classmethod,但事实并非如此。@classmethod从s中取出add,它应该可以工作。
| 归档时间: |
|
| 查看次数: |
1004 次 |
| 最近记录: |