If we do class inheritance, I’d say a reasonable assumption would be that this code would work:
class AddsFunct:
def __init__(self):
self.greet1 = "hello"
class AddsFunct2:
def __init__(self):
self.greet2 = "world"
class FullName(AddsFunct, AddsFunct2):
def __init__(self, name, surname):
super(AddsFunct, self).__init__()
super(AddsFunct2, self).__init__()
self.name = name
self.surname = surname
def printer(self):
print(self.greet1 + " " + self.name + " " + self.surname + " " + self.greet2)
fullname = FullName("John", "Doe")
fullname.printer()
The only way I could make this run is changing the super calls to:
class FullName(AddsFunct, AddsFunct2):
def __init__(self, name, surname):
super().__init__()
super(AddsFunct, self).__init__()
self.name = name
self.surname = surname
How is this supposed to be done in a clean and simple way ?
>Solution :
The class you pass to super will point to where in the MRO (Method Resolution Order) will start looking for the parent method. Instead, you can simply refer to classes directly.
class FullName(AddsFunct, AddsFunct2):
def __init__(self, name, surname):
AddsFunct.__init__(self)
AddsFunct2.__init__(self)
self.name = name
self.surname = surname
The another option, which avoids the need to refer to the classes directly, but requires changing all the parent classes, is to make them call super by themselves:
class AddsFunct:
def __init__(self):
super().__init__()
self.greet1 = "hello"
class AddsFunct2:
def __init__(self):
super().__init__()
self.greet2 = "world"
class FullName(AddsFunct, AddsFunct2):
def __init__(self, name, surname):
super().__init__()
self.name = name
self.surname = surname
This will call all the supers in MRO, eventually ending up at objects
class __init__
.