用 super 继承 python 中的两个 类。你能用 super() 调用 parent init 方法吗?

Inheriting form two classes in python with super. can you call parent init methods with super()?

假设这样:

class Father():
    def __init__(self,fathername):
        self.papa = f"The father is {fathername.upper()}"

class Mother():
    # Mother class is COMPLETELY DIFFERENT AS Father.
    # The important thing is that they both built an attribute each.
    def __init__(self,mothername):
        self.mama = f"the mother is {mothername.lower()}"
        
class Child3(Father,Mother):
    def __init__(self,name,fathername,mothername):
        Father.__init__(self,fathername)
        Mother.__init__(self,mothername)
        self.name=name

以下两个作品:

c = Child3('Noa',fathername='J',mothername='M')
c = Child3('Noa','J','M')

到目前为止一切顺利。 但是假设我想从几个 class 继承(不是多重嵌套继承,而是一个 class 从几个不继承任何其他东西的继承) 我如何使用 super() 来初始化 parent classes?

以下无效:

class Child4(Father,Mother):
    def __init__(self,name,fathername,mothername):
        super().__init__(self,fathername=fathername,mothername=mothername)
        self.name=name

TypeError: init() got multiple values for argument 'fathername'

之前的一些咨询:

  1. How does Python's super() work with multiple inheritance? 这是一个非常完整的答案,我已经在一段时间前投票了。尽管如此,这个问题有点不同,并不完全是我在这里问的情况,即 MRO(方法解析顺序)在这里并不重要。我想实现一种硬编码初始化 parent classes 以访问所有属性的方法。在提到的问题中,得票最多的答案在 parent classes 中没有属性。在投票第二多的答案中,parent classes 也没有属性。然而,在另一个答案中,有一个非常完整的多继承 MRO 解释,这也不是这里的重点,因为只有一个继承级别。

  2. 在另一个有很多赞成票的问题中,parents class 没有任何属性:Calling parent class __init__ with multiple inheritance, what's the right way?

  3. 这是更接近的一个,但没有使用 super() 实现解决方案 实际上建议放弃继承范式

  4. 这是一个接近的:calling init for multiple parent classes with super? 但我看到 parent classes 中有 super() ,因为目标是适得其反不必修改 parent classes.

为了理解这个例子的使用以及为什么我必须使用继承认为第一个 parent class 调用一个 API 并执行几个 1000s 代码 NLP提取 API 响应数据的过程。第二个parentclass也是如此。然后 child class 将尝试使用 NLP 进一步比较两者。

classes 母亲和父亲已给出。它们不是我编码的。我没有机会修改它们。他们不依赖任何其他 class.

一个 child 有一个 母亲和一个父亲,最好设计成在其中包含母亲和父亲属性。我认为以下 class 定义对您的情况更有意义:

class Person():
    def __init__(self, name):
        self._name = name

    def get_name(self):
        return self._name

class Child(Person):
    def __init__(self, name, father_name, mother_name):
        super().__init__(name)
        self._father = Person(father_name)
        self._mother = Person(mother_name)

    def get_father_name(self):
        return self._father.get_name()

    def get_mother_name(self):
        return self._mother.get_name()


child = Child('Peter', 'Joseph', 'Mary')
print(child.get_name(), child.get_father_name(), child.get_mother_name())

打印:

Peter Joseph Mary