python - 从父类继承时如何将 args 传递给 super?
问题描述
编辑:我下面的评论应该被忽略,因为我仍然需要弄清楚如何在这里传递参数:
A1 = 孩子('鸟','它会飞','是')
只使用get,不会削减它。
这是我的代码示例,我不想复制和粘贴所有内容,因为它看起来有点矫枉过正。我的问题是这个。。
Name 和 Description 属性在 Parent 类中设置为字符串。A1 是 Child 类的一部分。
class Parent:
def __init__(self, Name, Description, arg3):
self.__Name = "Dog"
self.__Description = "It walks"
self.__arg3 = arg3
def getName(self):
return self.__Name
def getDescription(self):
return self.__Description
def getArg3(self):
return self.__arg3
def setName(self, Name):
self.__Name = Name
def setDescription(self, Description):
self.__Description = Description
def setArg3(self, Code):
self.__Arg3 = Arg3
```
class Child(Parent):
def __init__(self):
super().__init__()'''
A1 = Child('Bird','It flies','Yes')
A1.getName()
A1.getDescription()
A1.getArg3()
OUTPUT:
DOG #Why is this not overidden by 'BIRD'
IT WALKS #Same for this
Yes #This one is fine
通过在此处给出参数 A1 = Child('Bird','It flies', 'Yes' )很容易覆盖 ARG3 。Name 和 Description 继续从 Parent 获取它们的属性。为什么是这样?
解决方案
您的子类的init没有收到您传递给它的参数。它应该看起来像
class Child(Parent):
def __init__(self, Name, Description, arg3):
super().__init__(Name, Description, arg3)
此外,无论您传递什么参数,Parent 类都会设置 __Name 和 __Description。
推荐阅读
- instagram-graph-api - Instagram图形API,如何在不分页的情况下查询我帐户的所有媒体
- javascript - django 模板创建中的脚本错误
- cart - 在 prestashop 1.7 购物车预览图标中将相同产品的项目分组以仅计算一个
- python - Python 运行 Bash 脚本并获取输出
- azure-devops - 运行 Power BI 查询以获取 Azure DevOps 数据的 AssignedTo 列上的 DataFormat.Error
- spring - snmp4j commandresponder 作为 springBatch 作业的 ItemReader
- python - YoloV5 在第一个纪元被杀死
- java - 在使用之前我需要检查可选对象本身的 null 吗?- 可选对象 == 空
- javascript - React:道具更改时重新渲染组件
- django - 如何在 django 启动期间创建类的实例