Python:在基类ini中调用重写的基类方法

2024-10-03 17:24:41 发布

您现在位置:Python中文网/ 问答频道 /正文

考虑以下运行python2.7的类:

class S(object):
  def __init__(self):
    print 'Si'
    self.reset()

  def reset(self):
    print 'Sr'
    self.a=0

class U1(S):
  def reset(self):
    print 'U1r'
    self.b=0
    super(S,self).reset()

理想的功能是

  1. 创建基类的实例调用其reset方法
  2. 创建派生类的实例将调用其reset方法,并调用基类的reset方法。在

我得到(1):

^{pr2}$

但不是(2):

>>> print U1().b
Si
U1r
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "tt.py", line 4, in __init__
    self.reset()
  File "tt.py", line 14, in reset
    super(S,self).reset()
AttributeError: 'super' object has no attribute 'reset'

得到我想要的东西最干净的方法是什么?我认为这个错误与类成员关系的构建顺序有关,但是我无法从文档中找到它。在


Tags: 方法inselfobjectinitdeflineclass
2条回答

您应该在U1.reset()中调用super(U1, self).reset()。使用super时,应该始终将当前类的名称作为第一个参数传递,而不是父类的名称。As stated in the docs

super(type[, object-or-type])

Return a proxy object that delegates method calls to a parent or sibling class of type

super将在您提供的type的父级或同级上查找方法。当您提供父类时,它将尝试在父类的父类/同级上查找reset的实现,这将失败。在

应该是:

super(U1, self).reset()

在我的脑子里,我把“超级(U1,…”读作“U1的父母”)来保持它的直线。在

相关问题 更多 >