Python 子实例 属性 似乎被父实例 属性 覆盖

Python child instance property appears to be overridden by parent property

我正在学习 Python3 并编写一些概念性的代码来帮助我理解。我遇到了一个简单的 class 继承示例的问题,其中来自子 class 的实例变量似乎被父变量覆盖。

我以各种形式尝试了以下代码,并为了这个问题的目的对其进行了简化。当我在 Child [=34= 中使用 self.name 时,我无法弄清楚为什么 Child 对象自己的 __str__() 方法指的是 Parent 的 name 属性 ] 来引用 Child 的 name 属性(就好像 self.namesuper().name 替换了)。

class Parent():

    """ Parent class that will take a name or default to 'Default Parent'.
    """

    def __init__(self, name="Default Parent"):
        self.name = name

    def __str__(self):
        return f'Parent: I am {self.name}'

class Child(Parent):

    """ Child class inheriting from Parent class
    """

    def __init__(self, name="Default Child"):
        # setting self.name to the name passed in during Child instantiation
        self.name = name
        # not passing self.name so parents's self.name will be defaulted to "Default Parent"
        super().__init__() 

    def __str__(self):
        # self.name prints "Default Parent"
        # The property self.name in Child appears to be overridden.
        # Thought self.name here refers to the instant variable belonging to the instance of Child and not super().name.
        return f'Child: I am {self.name}'

我对此进行了如下测试:

p1 = Parent("Parent 1")
c1 = Child("Child 1")
print(p1)
print(c1)

我期望返回这些结果:

Parent: I am Parent 1
Child: I am Child 1

相反,我得到了这些:

Parent: I am Parent 1
Child: I am Default Parent

您在 Child 中设置 self.name 后调用 super().__init__()。这将覆盖 属性。相反,将 name 参数传递给父 init。

class Child(Parent):

    """ Child class inheriting from Parent class
    """

    def __init__(self, name="Default Child"):
        super().__init__(name=name)