Home > Mobile >  How to specify which parent class to use in super( ) function in python?
How to specify which parent class to use in super( ) function in python?

Time:10-30

My Objective: Create the method named [identify2] in child class that invokes the [identify] method from Parent2 class. This must be done using super() keyword.

My problem: the method names in both parent class are the same. But I want to pertain only to the method of parent2 class using super() keyword. what should I do?

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
  

CodePudding user response:

super can be called with type and object parameters, see the documentation. The type parameter determines after which class in the mro order the search for the method will start. In this case, to get a method of Parent2 the search should start after 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 gives:

This method is called from Child
This method is called from Parent2
  • Related