从基类扩展方法时的TypeError

时间:2016-12-21 19:26:49

标签: python inheritance methods

我试图测试一个简单的Python继承案例,但是我在理解Python解释器吐出的错误时遇到了问题。

class Mainclass(object):
    """
     Class to test the inheritance
    """
    def __init__(self,somevalue):
        self.somevalue = somevalue
    def display(self):
        print(self.somevalue)


class Inherited(Mainclass):
    """
    Inherited class from the Main Class
    """
    def display(self):
        print("**********")
        Mainclass.display()
        print("**********")

c = Inherited(100)
c.display()

我只是想在Inherited类的显示输出中添加星号,那么为什么它会因以下错误而失败?

Traceback (most recent call last):
line 21, in <module>
c.display()
line 17, in display
Mainclass.display()
TypeError: display() missing 1 required positional argument: 'self'

2 个答案:

答案 0 :(得分:5)

调用它时,需要将self从继承类的display方法传递给Mainclass.display()方法。所以你的代码变成了:

class Mainclass(object):
  """
   Class to test the inheritance
  """
  def __init__(self,somevalue):
      self.somevalue = somevalue
  def display(self):
      print(self.somevalue)


class Inherited(Mainclass):
  """
  Inherited class from the Main Class
  """
  def display(self):
      print("**********")
      Mainclass.display(self)
      print("**********")

c = Inherited(100)
c.display()

希望这有帮助! :)

答案 1 :(得分:1)

正确的方法是像这样打电话给super

# Python 2.7 using new style classes
class Inherited(Mainclass):
"""
Inherited class from the Main Class
"""
    def display(self):
        print("**********")
        super(Mainclass,self).display(self)
        print("**********")

或者这样

# Python 3.x
class Inherited(Mainclass):
"""
Inherited class from the Main Class
"""
    def display(self):
        print("**********")
        super().display(self)
        print("**********")