Apa*_*nti 0 python methods inheritance
我试图测试一个简单的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()
Run Code Online (Sandbox Code Playgroud)
我只是试图在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'
Run Code Online (Sandbox Code Playgroud)
小智 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()
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助!:)