从子类继承的属性打印子对象而不是父对象的字符串

Tod*_*odd 2 python inheritance class

我知道许多关于Python中类继承的主题已经解决,但我找不到解决这个特定问题的线程.

编辑:我正在运行Python 3.5.5.

码:

class Parent():
    def __init__(self, parentParam="parent param"):
        self.parentParam = parentParam

class Child(Parent):
    def __init__(self, childParam = "child param"):
        self.childParam = childParam
        super().__init__(self)

child = Child()
print(child.childParam)
print(child.parentParam)
Run Code Online (Sandbox Code Playgroud)

输出:

child param
<__main__.Child object at 0x0000017CE7C0CAC8>
Run Code Online (Sandbox Code Playgroud)

为什么会child.parentParam返回子对象而不是字符串"parent param"?我觉得应该打印出Parent类的默认字符串集.这似乎与我在本教程中遵循的语法相同.

感谢大家.

Pat*_*ner 5

因为你为self超级调用提供了child(aka )的实例:

class Child(Parent):
    def __init__(self, childParam = "child param"):
        self.childParam = childParam
        super().__init__(self) # here you override the default by supplying this instance
Run Code Online (Sandbox Code Playgroud)

使用:

class Child(Parent):
    def __init__(self, childParam = "child param"):
        self.childParam = childParam
        super().__init__() 
Run Code Online (Sandbox Code Playgroud)

相反,你得到这个输出:

child param
parent param
Run Code Online (Sandbox Code Playgroud)