Consider the following python code:
class Parent(object):
def __init__(self, name, serial_number):
self.name = name
self.serial_number = serial_number
class ChildA(Parent):
def __init__(self, name, serial_number):
self.name = name
self.serial_number = serial_number
super(ChildA, self).__init__(name = self.name, serial_number = self.serial_number)
def speak(self):
print("I am from Child A")
class ChildB(Parent):
def __init__(self, name, serial_number):
self.name = name
self.serial_number = serial_number
super(ChildB, self).__init__(name = self.name, serial_number = self.serial_number)
def speak(self):
print("I am from Child B")
class GrandChild(ChildA, ChildB):
def __init__(self, a_name, b_name, a_serial_number, b_serial_number):
self.a_name = a_name
self.b_name = b_name
self.a_serial_number = a_serial_number
self.b_serial_number = b_serial_number
super(GrandChild, self).__init_( something )
When running the super
function in GrandChild, what is the proper way to format the __init__
arguments so that ChildA and ChildB both get the correct arguments?
Also how do you access the two different versions of the speak
method (ChildA's version and ChildB's version) from within the GrandChild class?
so, when you call super from the grandchild,
ChildA
's__init__
method will be called because super follows the__mro__
property (parents left to right then grandparents left-to-right, then great grandparents, ...)Since
ChildA
's init also calls super, then all the super calls will be chained, calling child b's__init__
and eventually the parent init.For that to work, your interface generally needs to be consistent. That is positional arguments need to mean the same things, and be in the order.
In situations where that's not the case, keyword arguments may work better.
Also note that in your code
name
andserial
are reused as instance properties between all the classes and that's probably not what you want.