educative.io

Hybrid inheritance - what happens when there are shared properties

A user asked this:

class Engine: #Parent class 
	def setPower(self, power): 
		self.power = power 


class CombustionEngine(Engine): #Child class inherited from Engine 
	def setTankCapacity(self, tankCapacity): 
		self.tankCapacity = tankCapacity 

	def getIt(self): 
		self.number = 5 
		return self.number 
 

class ElectricEngine(Engine): #Child class inherited from Engine 
  def setChargeCapacity(self, chargeCapacity): 
	  self.chargeCapacity = chargeCapacity 

  def getIt(self): 
    self.number = 7
    return self.number 

class BailgaadiEngine(Engine): #Child class inherited from Engine 
  def setChargeCapacity(self, chargeCapacity): 
	  self.chargeCapacity = chargeCapacity 
  
  def getIt(self): 
    self.number = 9 
    return self.number

#Child class inherited from CombustionEngine and ElectricEngine 

class HybridEngine(BailgaadiEngine, CombustionEngine, ElectricEngine):
  def printDetails(self):
    print("Power:", self.power)
    print("Tank Capacity:", self.tankCapacity)
    print("Charge Capacity:", self.chargeCapacity)

car = HybridEngine()
car.setPower("2000 CC")
car.setChargeCapacity("250 W")
car.setTankCapacity("20 Litres")
car.printDetails()
print(car.getIt())

This is Waleed from Educative. Thank you for reaching out to us!

If inherited classes have properties with the same names, the first parameter in the child class definition will be given preference. In the case above, the first parameter of HybridEngine is BailgaadiEngine, so when the car object calls the getIt() method, the getIt() method in the BailgaadiEngine class is called.

Try changing the order of HybridEngine parameters and observe the change in output.

Best Regards,
Waleed Khalid | Developer Advocate
Educative