Python 2.3调用超类方法

时间:2013-10-15 07:47:40

标签: python superclass super derived-class

在以下Python 2.3脚本中调用基类函数时遇到问题。 在审阅这篇文章之后:

Call a parent class's method from child class in Python?

我已经生成了这一小段代码:

class Base(object):

    def func(self):
        print "Base.func"

class Derived(Base):

    def func(self):
        super(Base, self).func()
        print "Derived.func"

Derived().func()
上面的

代码会生成此错误:

Traceback (most recent call last):
  File "py.py", line 13, in ?
    Derived().func()
  File "py.py", line 10, in func
    super(Base, self).func()
AttributeError: 'super' object has no attribute 'func'

我错过了什么?

1 个答案:

答案 0 :(得分:16)

您应该为要升级的派生类提供super,而不是基类:

super(Derived, self).func()

现在你正试图访问Base的超类的func方法,它甚至可能不存在。