python - 如何在Python中的super()函数中指定使用哪个父类?

标签 python oop inheritance overriding

我的目标:在子类中创建名为 [identify2] 的方法,该方法从 Parent2 类调用 [identify] 方法。这必须使用 super() 关键字来完成。

我的问题:两个父类中的方法名称相同。但我只想涉及使用 super() 关键字的parent2 类的方法。我该怎么办?

class Parent1:
  def identify(self):
    return "This method is called from Parent1"
    
class Parent2:
  def identify(self):
    return "This method is called from Parent2"
    
# declare child class here
class child(Parent1, Parent2):
  def identify(self):
    return "This method is called from Child"
  def identify2(self):
    super().identify()  # I want to call the method of Parent2 class, how?     
  
  
child_object = child()
#                                           Expected output:
print( child_object.identify() )        # This method is called from Child
print( child_object.identify2() )       # This method is called from Parent2
  

最佳答案

super 可以使用类型和对象参数进行调用,请参阅 documentation 。类型参数确定在 mro 顺序中的哪个类之后开始搜索方法。在本例中,要获取 Parent2 的方法,搜索应在 Parent1 之后开始:

class Parent1:
    def identify(self):
        return "This method is called from Parent1"
    
class Parent2:
    def identify(self):
        return "This method is called from Parent2"
    
# declare child class here
class Child(Parent1, Parent2):
    def identify(self):
        return "This method is called from Child"
    
    def identify2(self):
        return super(Parent1, self).identify()
  
  
child_object = Child()
#                                           Expected output:
print( child_object.identify() )        # This method is called from Child
print( child_object.identify2() )       # This method is called from Parent2

这给出:

This method is called from Child
This method is called from Parent2

关于python - 如何在Python中的super()函数中指定使用哪个父类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69732726/

相关文章:

java - 单一责任原则和组织 DI 接口(interface)的正确方法

java - 使用 getInstance 的单例与公共(public)声明

c++ - 从复合模式结构中删除元素

python - 创建一个被视为列表但具有更多功能的 python 类?

python - 非相邻对之间的 pct_change

java - OOP (Java) - 生成对象的最佳方式

php - CakePHP 中 $this-> 的含义

python - 如何在lxml解析中获得准确的日期?

Python newb : What's preventing this function from printing?

python - 用 pandas 设置标题