python-3.x 如果子类中的父类属性同名,如何调用它们?

ie3xauqp  于 2023-06-25  发布在  Python
关注(0)|答案(1)|浏览(141)
class Parent:
    def __init__(self):
        self.name = "Parent"

class Child(Parent):
    def __init__(self):
        super().__init__()
        self.name = "Child"

    def print_names(self):
        print("Child name:", self.name)

    # Below line of code is giving error
        print("Parent name:", super().name)

假设我们有两个类Parent和Child,Child继承Parent类。两者都有相同的属性名,但当我调用super().name时,它会出错请帮助

zzwlnbp8

zzwlnbp81#

如果你创建了一个子类的对象,它将覆盖,并且总是给予你Child
而是创建一个Parent类的对象并调用其属性

class Parent:
    def __init__(self):
        self.name = "Parent"

class Child(Parent):
    def __init__(self):
        self.name = "Child"

    def print_names(self):
        print("Child name:", self.name)

        p = Parent()
        print("Parent name:", p.name)

c1 = Child()
c1.print_names()

'Child name: Child'
'Parent name: Parent'
除此之外,你可以看看这个播放列表,它以最简单的方式解释了OOP https://youtube.com/playlist?list=PLAvWroJsSxGn4LOCLdxL4HjUije65mP5K

相关问题