【发布时间】:2019-07-04 14:29:20
【问题描述】:
我正在学习 Python 3 并编写概念性代码以帮助我理解。我在一个简单的类继承示例中遇到了一个问题,其中来自子类的实例变量似乎被父变量覆盖。
我已经以各种形式使用了以下代码,并出于此问题的目的对其进行了简化。当我在 Child 类中使用 self.name 来引用 Child 的 name 属性时,我无法弄清楚为什么 Child 对象自己的 __str__() 方法引用了 Parent 的 name 属性(它是好像self.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
相反,我得到了这些:
Parent: I am Parent 1
Child: I am Default Parent
【问题讨论】:
标签: python class inheritance instance