首页 > 解决方案 > 从父类继承时如何将 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 获取它们的属性。为什么是这样?

标签: pythonsuper

解决方案


您的子类的init没有收到您传递给它的参数。它应该看起来像

class Child(Parent):
    def __init__(self, Name, Description, arg3):
        super().__init__(Name, Description, arg3)

此外,无论您传递什么参数,Parent 类都会设置 __Name 和 __Description。


推荐阅读