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

时间:2019-07-04 14:29:20

标签: python class inheritance instance

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

我以各种形式处理了以下代码,并出于这个问题的目的对其进行了简化。当我在Child类中使用__str__()来引用{{1}时,我不知道为什么Child对象自己的name方法引用了Parent的self.name属性}}的子属性(就好像nameself.name取代了一样。)

super().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

1 个答案:

答案 0 :(得分:1)

super().__init__()中设置self.name后,您正在呼叫Child。这将覆盖该属性。而是将name参数传递给父init。

class Child(Parent):

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

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