【问题标题】:Attribute inherited from child class prints child object not string from parent从子类继承的属性打印子对象而不是来自父类的字符串
【发布时间】:2018-10-10 17:34:33
【问题描述】:

我知道关于 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)

输出:

child param
<__main__.Child object at 0x0000017CE7C0CAC8>

为什么child.parentParam返回的是子对象而不是字符串"parent param"?我觉得它应该打印出为 Parent 类设置的默认字符串。这似乎与我在this tutorial 中使用的语法相同。

谢谢大家。

【问题讨论】:

    标签: python class inheritance


    【解决方案1】:

    因为您将子实例(又名self)提供给超级调用:

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

    用途:

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

    相反,您会得到以下输出:

    child param
    parent param
    

    【讨论】:

    • 感谢您简洁的回答。我现在看到了问题。
    【解决方案2】:

    您对super 的呼叫是错误的。在使用self 参数将方法调用委托给超类时,不必显式传递它(参见documentation 中显示的典型用法示例)。

    在 Python 3 中,对不带参数的 super() 的调用等效于 super(CurrentClass, self).method(arg)——这是在 Python 2 中可以完成的唯一方法——使得在调用超类时不再需要指定它方法。

    所以发生了什么,因为您在代码中传递了它,它被解释为覆盖为 parentParam 参数指定的默认值。

    这是正确的做法和结果:

    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__()  # NO NEED TO PASS self.
    
    
    child = Child()
    print(child.childParam)   # -> child param
    print(child.parentParam)  # -> parent param
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-05-03
      • 1970-01-01
      • 1970-01-01
      • 2020-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多