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(). Each class's __name__ is its name as text, so the list comprehension in the example below turns the classes into names. Last in the order comes object, a class built into Python: every class has it as a parent, even if you don't write it.class Car:
def move(self):
return 'drives'
class Plane:
def move(self):
return 'flies'
class FlyingCar(Car, Plane):
pass
# drives: Car is listed first
print(FlyingCar().move())
# The search order, as class names
classes = FlyingCar.__mro__
order = [c.__name__ for c in classes]
print(order)
# ['FlyingCar', 'Car', 'Plane', 'object']Mixins
Small helper classes that each add one behaviour are called mixins. Below,
JsonMixin has just one method, to_json(), and Truck gets it by listing the mixin first, before its main parent, Vehicle. Inside it, self.__dict__ is a dictionary of every attribute stored on the object, and json.dumps(d, sort_keys=True) turns that into JSON text, with the keys in A to Z order. Truck has no __init__ of its own, so Python searches the MRO and uses Vehicle's.import json
class JsonMixin:
def to_json(self):
d = self.__dict__
return json.dumps(d, sort_keys=True)
class Vehicle:
def __init__(self, name):
self.name = name
# One mixin, then the main parent
class Truck(JsonMixin, Vehicle):
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)
# Becomes _Sneaky__balance: no clash
self.__balance = 0
s = Sneaky(100)
# The parent's value is untouched:
print(s._BankAccount__balance) # 100
print(s._Sneaky__balance) # 0
# print(s.__balance) gives an AttributeErrorself.__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'll usually use a single underscore instead (_balance), a polite "please don't touch" sign that the next lesson covers.