【问题标题】:How to specify which parent class to use in super( ) function in python?如何在 python 的 super() 函数中指定使用哪个父类?
【发布时间】:2021-12-12 09:28:30
【问题描述】:

我的目标:在调用 Parent2 类的 [identify] 方法的子类中创建名为 [identify2] 的方法。这必须使用 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
  

【问题讨论】:

    标签: python oop inheritance overriding


    【解决方案1】:

    super 可以用类型和对象参数调用,参见documentation。 type 参数确定在 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-18
      • 2020-04-06
      • 1970-01-01
      相关资源
      最近更新 更多