英文:
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 = "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>'Child name: Child'
<br>
<output>'Parent name: Parent'
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论