I have multiple parent classes with methods of the same name that are inherited by the child class. I'm wondering if it is possible to specify which parent class the child class uses in the call to super(). Depending on what argument is passed, I would want my child class to use the methods from the specified parent class. Thanks in advance
class ParentOne:
def __init__(self, payload):
self.payload = payload
def foo(self):
message = f"From ParentOne: {self.payload}"
return message
class ParentTwo:
def __init__(self, payload):
self.payload = payload
def foo(self):
message = f"From ParentTwo: {self.payload}"
return message
class Child(ParentOne, ParentTwo):
def __init__(self, payload):
## How to specify which parent to init with??
super().__init__(payload=payload)
You do this very much as you described: pass in the desired parent and use it.
Since you're not using the parent-resolution mechanism, you'll have to directly call the desired __init__
as a class method, and supply the child as an explicit argument:
class Child(ParentOne, ParentTwo):
def __init__(self, payload, parent):
## How to specify which parent to init with??
parent.__init__(self, payload=payload)
child1 = Child("cargo 1", ParentOne)
child2 = Child("cargo 2", ParentTwo)
Output:
init 1 used
init 2 used