So far you have seen a class inherit from one parent. Python lets it do more:
class FlyingCar(Car, Plane) makes FlyingCar pull methods from both parents.Method resolution order
When two parents have the same method name, Python picks one by following a fixed rule called the MRO. It checks the class itself first, then walks through the parent list from left to right. You can see this exact order with
ClassName.__mro__ or ClassName.mro().class Car:
def move(self):
return 'drives'
class Plane:
def move(self):
return 'flies'
class FlyingCar(Car, Plane):
pass
print(FlyingCar().move()) # drives: Car is listed first
print([k.__name__ for k in FlyingCar.__mro__]) # ['FlyingCar', 'Car', 'Plane', 'object']Mixins and super()
Small helper classes that each add one behaviour are called mixins. A common pattern is a
JsonMixin with just a to_json() method, combined with your main parent. Because Python walks the MRO to find methods and call super(), every class in a cooperative chain should accept flexible arguments โ usually **kwargs โ so each one can pass anything it does not need straight through.class JsonMixin:
def to_json(self):
return f'{{"name": "{self.name}"}}'
class Vehicle:
def __init__(self, name):
self.name = name
class Truck(JsonMixin, Vehicle): # one mixin plus the main parent
pass
t = Truck('Hauler')
print(t.to_json()) # {"name": "Hauler"}Name mangling: double underscore names
class BankAccount:
def __init__(self, balance):
self.__balance = balance
class Sneaky(BankAccount):
def __init__(self, balance):
super().__init__(balance)
self.__balance = 0 # stored as _Sneaky__balance: no clash
s = Sneaky(100)
print(s._BankAccount__balance) # 100: the parent's value is untouched
print(s._Sneaky__balance) # 0
# print(s.__balance) # AttributeError: no attribute called __balanceself.__x inside a class becomes _ClassName__xWriting
self.__balance tells Python to store it as _BankAccount__balance. A subclass that accidentally writes the same name gets its own mangled slot, so nothing is silently overwritten. It is a guard against collisions โ not real privacy, because anyone can still reach the mangled name. For everyday code you will usually prefer the single-underscore convention from an earlier lesson.