0

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

我已经以各种形式使用了以下代码,并出于这个问题的目的对其进行了简化。当我在 Child 类内部使用来引用 Child的属性时,我无法弄清楚为什么 Child 对象自己的__str__()方法引用了 Parent 的属性(好像被替换为)。nameself.namenameself.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
4

1 回答 1

1

super().__init__()在设置self.namein后打电话Child。这是覆盖属性。相反,将 name 参数传递给父 init。

class Child(Parent):

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

    def __init__(self, name="Default Child"):
        super().__init__(name=name) 
于 2019-07-04T14:30:53.863 回答