是否可以在多重继承中从具有相同名称的第二个类调用函数



假设我们有三个类

class Father:
def __init__(self, father_name) -> None:
self.father_name = father_name
def name(self):
print(f"Father name : {self.father_name}")
class Mother:
def __init__(self, mother_name) -> None:
self.mother_name = mother_name
def name(self):
print(f"Mother name : {self.mother_name}")
class Son(Father, Mother):
def __init__(self, father_name, mother_name):
Father.__init__(self, father_name)
Mother.__init__(self, mother_name)
me = Son('Jamie', 'Jack', 'Linda')
me.name()

输出为:

父亲姓名:Jack

如何在不更改函数名称的情况下从Mother类而不是Father类调用name方法,以便输出为:

母亲姓名:Linda

您的代码中有很多问题。

  • 您的示例不起作用
  • 而不是:
Father.__init__(self, father_name)
Mother.__init__(self, mother_name)

您应该使用:

super(Father, self).__init__(self, father_name)
super(Mother, self).__init__(self, mother_name)

(假设你真的想在这里继承(

  • Father的name方法之所以被调用,是因为它被称为MRO(方法解析顺序(。值得一读,但不是你应该尝试修改的。如果你只想叫母亲的名字,而不想叫父亲的名字,只需说Son(Mother, Father)而不是Son(Father, Mother)

  • 正如@Mark所提到的,这不是一个合理的用例遗产孩子父母,而不是的父母。

总而言之,如果你想用继承来做这件事,那就是我的建议:

class Son(Mother, Father):
def __init__(self, father_name, mother_name):
super(Father, self).__init__(self, father_name)
super(Mother, self).__init__(self, mother_name)
def name(self, ParentClass):
return super(ParentClass, self).name()
me = Son('Jack', 'Linda')
me.name(Mother)
me.name(Father)

但是,我认为更合理的方法是使用属性。

class Son():
def __init__(self, father_name, mother_name):
self.father = Father(father_name)
self.mother = Mother(mother_name)
me = Son('Jack', 'Linda')
me.mother.name()
me.father.name()

或者,更好的是,使用现有的"父对象"创建一个"子"。这样你就可以创建多个父母相同的人。

class Son():
def __init__(self, father, mother):
self.father = father
self.mother = mother
mother = Mother('Linda')
father = Father('Jack')
me = Son(mother, father)
me.mother.name()
me.father.name()

你不应该做这样的事情,因为它看起来很糟糕。

Python中有MRO(方法解析顺序(概念,如果您不想深入研究多重继承,您应该了解这一点。

你的问题的答案是交换父亲和母亲混合

class Son(Mother, Father):
def __init__(self, my_name, father_name, mother_name):
self.my_name = my_name            
Father.__init__(self, father_name)
Mother.__init__(self, mother_name)

不过,请避免使用Class.__init__的原始用法。__init__不是对象创建,而是实例字段初始化,可能会导致意外结果。

最新更新