Reputation: 1
I've only been learning python for a week, before that I didn't really understand the concept of inheritance, I want to ask, how should I use child_class(parent1, parent2)?
thank you,
here's my code I attached
class Mobil:
def __init__(self, warna, plat, nomor_rangka, nomor_mesin):
self.warna = warna
self.plat = plat
self.nomor_rangka = nomor_rangka
self.nomor_mesin = nomor_mesin
class MobilBBM(Mobil):
def __init__(self, warna, plat, nomor_rangka, nomor_mesin, bbm):
super().__init__(warna, plat, nomor_rangka, nomor_mesin)
self.bbm = bbm
class MobilListrik(Mobil):
def __init__(self, warna, plat, nomor_rangka, nomor_mesin, baterai):
super().__init__(warna, plat, nomor_rangka, nomor_mesin)
self.baterai = baterai
class MobilHybrida(MobilListrik, MobilBBM):
def __init__(self, warna, plat, nomor_rangka, nomor_mesin, baterai, bbm):
super().__init__(warna, plat, nomor_rangka, nomor_mesin, baterai, bbm)
mobil = MobilHybrida('Hitam','B','12','13','Pertalite','Water')
Upvotes: 0
Views: 4659
Reputation: 530833
MobilListrik
and MobilBBM
share 4 arguments, but each expects a different 5th argument. You can't simply pass all 6 arguments to super().__init__
as positional arguments and expect the correct ones to go to the correct parent.
The standard advice is to use keyword arguments with __init__
in a multiple inheritance situation. Each __init__
will grab the arguments they expect and pass the rest on up the tree.
class Mobil:
def __init__(self, *, warna, plat, nomor_rangka, nomor_mesin, **kwargs):
super().__init__(**kwargs)
self.warna = warna
self.plat = plat
self.nomor_rangka = nomor_rangka
self.nomor_mesin = nomor_mesin
class MobilBBM(Mobil):
def __init__(self, *, bbm, **kwargs):
super().__init__(**kwargs)
self.bbm = bbm
class MobilListrik(Mobil):
def __init__(self, *, baterai, **kwargs):
super().__init__(**kwargs)
self.baterai = baterai
# Note that MobilHybrida.__init__ doesn't even need to be defined.
class MobilHybrida(MobilListrik, MobilBBM):
pass
# I'm guessing at which values go with which parameters.
mobil = MobilHybrida(warna='Hitam', plat='B', nomor_rangka='12', nomor_mesin='13', bbm='Pertalite', baterai='Water')
Upvotes: 1