如何在子类中调用与父类同名的属性?

huangapple go评论55阅读模式
英文:

How to call parent class attributes in child class if they are of same name?

问题

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)
英文:
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)

Suppose we have two classes Parent and Child, Child inherit Parent class. Both have same attribute name, but when I am calling super().name , it is giving error Please help

答案1

得分: 0

如果您创建一个子类的对象,它将覆盖并始终给您返回
Child<br>
而不是这样,创建一个父类的对象并调用其属性

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

<output>'Parent name: Parent'<br>
<output>'Child name: Child'

此外,您可以查看以下播放列表,它以最简单的方式解释了面向对象编程:
https://youtube.com/playlist?list=PLAvWroJsSxGn4LOCLdxL4HjUije65mP5K

英文:

If you create an object of child class it will override and will always give you
Child<br>
Instead create a object of Parent class and call its attribute

class Parent:
    def __init__(self):
        self.name = &quot;Parent&quot;

class Child(Parent):
    def __init__(self):
        self.name = &quot;Child&quot;

    def print_names(self):
        print(&quot;Child name:&quot;, self.name)

        p = Parent()
        print(&quot;Parent name:&quot;, p.name)

c1 = Child()
c1.print_names()

<output>&#39;Child name: Child&#39;<br>
<output>&#39;Parent name: Parent&#39;

Along with this you can have a look of at this playlist it explains OOP in most easy way
https://youtube.com/playlist?list=PLAvWroJsSxGn4LOCLdxL4HjUije65mP5K

huangapple
  • 本文由 发表于 2023年6月15日 20:21:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/76482420.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定