编程语言
首页 > 编程语言> > Python 2.3调用超类方法

Python 2.3调用超类方法

作者:互联网

在以下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'

我错过了什么?

解决方法:

你应该给super你想要升级的派生类,而不是基类:

super(Derived, self).func()

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

标签:python,super,superclass,derived-class
来源: https://codeday.me/bug/20190713/1446530.html