Python course · Module 8: OOP in Python · Lesson 40 of 63
Quick answer: Inheritance lets a new class reuse an existing one. You write class MemberCart(ShoppingCart):, and MemberCart (the child class, or subclass) gets every method of ShoppingCart (the parent class, or base class). In the child you can add new methods and override old ones by writing a method with the same name. Inside an overriding method, super().total() runs the parent’s version, so you extend it instead of copying it, and super().__init__(owner) lets the parent set up its attributes first.
In this lesson you will learn:
- how to make a subclass that inherits methods from a base class
- how to add new methods and override existing ones
- how
super()calls the parent’s method and parent’s__init__ - how Python finds a method (the method resolution order) and how
isinstance()andissubclass()work with inheritance - a first look at multiple inheritance
Before you start: finish Lesson 39, Python Instance, Class and Static Methods and @property. You also need the ShoppingCart class from Lesson 38. All examples were run on Linux with Python 3.14.6 and gave exactly the same output on Python 3.15.2, the newest release on python.org. We use a plain total() method here, not a property, so the focus stays on inheritance.
Table of Contents
What is inheritance in Python?
Our shop now has members who get 10% off. A member cart is still a shopping cart, with an owner, items and a total. So instead of writing a new class from zero, we make MemberCart a subclass of ShoppingCart:
class ShoppingCart:
def __init__(self, owner):
self.owner = owner
self.items = {}
def add_item(self, name, price, quantity=1):
self.items[name] = (price, quantity)
def total(self):
return sum(price * quantity for price, quantity in self.items.values())
def __repr__(self):
return f"{type(self).__name__}({self.owner!r})"
class MemberCart(ShoppingCart):
pass
cart = MemberCart("Amna")
cart.add_item("pen", 1.5, 4)
cart.add_item("notebook", 3.0)
print(cart)
print(cart.total())
print(MemberCart.__bases__)
MemberCart('Amna')
9.0
(<class '__main__.ShoppingCart'>,)
class MemberCart(ShoppingCart):means “MemberCart is based on ShoppingCart”. The class in brackets is the base class (also called parent or superclass).MemberCarthas an empty body, yetMemberCart("Amna")worked andadd_item()andtotal()work. All of them came fromShoppingCart.__repr__printedMemberCart('Amna')because it usestype(self).__name__, the name of the object’s real class.__bases__shows the base classes of a class.
The Python tutorial explains how this works: “if a requested attribute is not found in the class, the search proceeds to look in the base class.”
You have used inheritance before. In Lesson 36, class OutOfStockError(Exception): made your own exception as a subclass of Exception.
Add new methods and override old ones
A subclass can do two things to change behaviour: add methods the parent does not have, and override methods by defining one with the same name:
class ShoppingCart:
def __init__(self, owner):
self.owner = owner
self.items = {}
def add_item(self, name, price, quantity=1):
self.items[name] = (price, quantity)
def total(self):
return sum(price * quantity for price, quantity in self.items.values())
def __repr__(self):
return f"{type(self).__name__}({self.owner!r})"
class MemberCart(ShoppingCart):
discount = 10 # percent
def total(self): # overrides ShoppingCart.total()
subtotal = sum(price * quantity for price, quantity in self.items.values())
return subtotal * (100 - self.discount) / 100
def points(self): # a new method only member carts have
return int(self.total())
normal = ShoppingCart("Bilal")
member = MemberCart("Amna")
for cart in (normal, member):
cart.add_item("pen", 1.5, 4)
cart.add_item("notebook", 3.0)
print(cart, cart.total())
print(member.points())
try:
normal.points()
except AttributeError as err:
print("AttributeError:", err)
ShoppingCart('Bilal') 9.0
MemberCart('Amna') 8.1
8
AttributeError: 'ShoppingCart' object has no attribute 'points'
- Bilal’s normal cart uses
ShoppingCart.total(): 9.0. - Amna’s member cart uses the new
MemberCart.total(): 9.0 minus 10% is 8.1. Python foundtotalinMemberCartfirst, so it never looked further. points()exists only on member carts, sonormal.points()raisedAttributeError.discount = 10is a class attribute ofMemberCart, likecurrencyin Lesson 38.
This works, but look at the first line of the new total(): it copies the parent’s code. If the parent’s total ever changes (say, to add tax), the copy goes out of date. super() fixes that.
super(): call the parent’s method
super() gives you access to the parent class’s methods from inside a subclass. The built-in functions docs say it returns “a proxy object that delegates method calls to a parent or sibling class”. In single inheritance, it simply means “the parent”:
class ShoppingCart:
def __init__(self, owner):
self.owner = owner
self.items = {}
def add_item(self, name, price, quantity=1):
self.items[name] = (price, quantity)
def total(self):
return sum(price * quantity for price, quantity in self.items.values())
def __repr__(self):
return f"{type(self).__name__}({self.owner!r})"
class MemberCart(ShoppingCart):
discount = 10 # percent
def total(self):
subtotal = super().total() # run ShoppingCart.total()
return subtotal * (100 - self.discount) / 100
member = MemberCart("Amna")
member.add_item("pen", 1.5, 4)
member.add_item("notebook", 3.0)
print(member.total())
print(ShoppingCart.total(member))
8.1
9.0
super().total()ranShoppingCart.total()for this cart and returned 9.0. The override then took 10% off, so the result is still 8.1, without copied code.ShoppingCart.total(member)calls the parent’s method directly, as the tutorial describes withBaseClassName.methodname(self, arguments). It works, butsuper()is the usual way, because you do not have to repeat the parent’s name.
The docs list “two typical use cases”: in single inheritance, super can “refer to parent classes without naming them explicitly, thus making the code more maintainable”. The second use case, multiple inheritance, comes at the end of this lesson.
super().__init__(): let the parent set up its attributes
Member carts also need a member ID. That means a new __init__. But the new __init__ replaces the parent’s one, so the parent’s setup (self.owner, self.items) must be called with super().__init__():
class ShoppingCart:
def __init__(self, owner):
self.owner = owner
self.items = {}
def add_item(self, name, price, quantity=1):
self.items[name] = (price, quantity)
def total(self):
return sum(price * quantity for price, quantity in self.items.values())
def __repr__(self):
return f"{type(self).__name__}({self.owner!r})"
class MemberCart(ShoppingCart):
discount = 10
def __init__(self, owner, member_id):
super().__init__(owner) # sets self.owner and self.items
self.member_id = member_id
def total(self):
return super().total() * (100 - self.discount) / 100
member = MemberCart("Amna", "M-1042")
member.add_item("pen", 1.5, 4)
print(vars(member))
print(member.total())
{'owner': 'Amna', 'items': {'pen': (1.5, 4)}, 'member_id': 'M-1042'}
5.4
super().__init__(owner)ranShoppingCart.__init__, which setowneranditems. Then the child addedmember_id.vars(member)shows all three attributes on the one object.- 4 pens at 1.50 = 6.0, minus 10% = 5.4.
Here is what happens when you forget that line:
class ShoppingCart:
def __init__(self, owner):
self.owner = owner
self.items = {}
def add_item(self, name, price, quantity=1):
self.items[name] = (price, quantity)
def total(self):
return sum(price * quantity for price, quantity in self.items.values())
def __repr__(self):
return f"{type(self).__name__}({self.owner!r})"
class MemberCart(ShoppingCart):
def __init__(self, owner, member_id):
self.member_id = member_id # super().__init__(owner) is missing
member = MemberCart("Amna", "M-1042")
print(vars(member))
member.add_item("pen", 1.5, 4)
{'member_id': 'M-1042'}
Traceback (most recent call last):
File "/home/learner/python-course/w39/step5_forgot_super_init.py", line 23, in <module>
member.add_item("pen", 1.5, 4)
~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^
File "/home/learner/python-course/w39/step5_forgot_super_init.py", line 7, in add_item
self.items[name] = (price, quantity)
^^^^^^^^^^
AttributeError: 'MemberCart' object has no attribute 'items'
The object has only member_id. ShoppingCart.__init__ never ran, so there is no items dictionary, and add_item() fails with AttributeError. If your subclass has its own __init__, call super().__init__(...) in it, usually as the first line.
How Python finds a method: the MRO
When you call a method, Python searches the object’s class first, then its base class, then that class’s base, and so on. This search order is called the method resolution order (MRO). It has an important effect: a parent method can call a child’s override.
class ShoppingCart:
def __init__(self, owner):
self.owner = owner
self.items = {}
def add_item(self, name, price, quantity=1):
self.items[name] = (price, quantity)
def total(self):
return sum(price * quantity for price, quantity in self.items.values())
def receipt(self):
return f"{self.owner} pays {self.total():.2f}" # which total()?
class MemberCart(ShoppingCart):
discount = 10
def total(self):
return super().total() * (100 - self.discount) / 100
for cart in (ShoppingCart("Bilal"), MemberCart("Amna")):
cart.add_item("pen", 1.5, 4)
cart.add_item("notebook", 3.0)
print(cart.receipt())
print(MemberCart.__mro__)
Bilal pays 9.00
Amna pays 8.10
(<class '__main__.MemberCart'>, <class '__main__.ShoppingCart'>, <class 'object'>)

receipt()is written only inShoppingCart. Both carts use it.- Inside
receipt(),self.total()starts a new search from the object’s own class. For Amna’s member cart, that findsMemberCart.total(), so her receipt says 8.10. - The tutorial describes exactly this: “a method of a base class that calls another method defined in the same base class may end up calling a method of a derived class that overrides it.”
__mro__shows the search order:MemberCart, thenShoppingCart, thenobject. Every class inherits fromobjectin the end.
Class methods work the same way: MemberCart.from_json(...) from Lesson 39 would find from_json() in ShoppingCart but get MemberCart as cls, so it builds a MemberCart.
isinstance() and issubclass()
An object of a subclass also counts as an object of its base class. isinstance() (from Lesson 26) respects that, while comparing type() with == does not:
class ShoppingCart:
def __init__(self, owner):
self.owner = owner
class MemberCart(ShoppingCart):
pass
normal = ShoppingCart("Bilal")
member = MemberCart("Amna")
print(isinstance(member, MemberCart), isinstance(member, ShoppingCart))
print(isinstance(normal, MemberCart))
print(type(member) == ShoppingCart)
print(issubclass(MemberCart, ShoppingCart), issubclass(ShoppingCart, MemberCart))
print(issubclass(MemberCart, object), issubclass(ValueError, Exception))
True True
False
False
True False
True True
- A member cart is a shopping cart:
isinstance(member, ShoppingCart)isTrue. A normal cart is not a member cart. type(member) == ShoppingCartisFalse, becausetype()gives only the exact class,MemberCart. Preferisinstance()for type checks.issubclass()checks classes instead of objects.ValueErroris a subclass ofException, which is whyexcept Exception:in Lesson 35 also catches aValueError.
Several subclasses, one loop
Inheritance is most useful when several subclasses share one base class. A loop can call shipping_cost() on each product, and each uses its own version. This is called polymorphism:
class Product:
def __init__(self, name, price):
self.name = name
self.price = price
def shipping_cost(self):
return 5.0
class DigitalProduct(Product):
def shipping_cost(self): # nothing to ship
return 0.0
class HeavyProduct(Product):
def __init__(self, name, price, weight_kg):
super().__init__(name, price)
self.weight_kg = weight_kg
def shipping_cost(self):
return super().shipping_cost() + 2.0 * self.weight_kg
order = [Product("pen", 1.5), DigitalProduct("e-book", 9.0), HeavyProduct("desk", 120.0, 15)]
for product in order:
print(f"{product.name:<7} {type(product).__name__:<15} shipping {product.shipping_cost():6.2f}")
print("total shipping:", sum(p.shipping_cost() for p in order))
pen Product shipping 5.00
e-book DigitalProduct shipping 0.00
desk HeavyProduct shipping 35.00
total shipping: 40.0
Productcharges a flat 5.00,DigitalProductoverrides it with 0.00, andHeavyProductextends it withsuper(): 5.00 + 2.00 × 15 kg = 35.00.HeavyProductcallssuper().__init__(name, price)and addsweight_kg.- The loop does not check types. It just calls
shipping_cost(). The format specs:<7and:6.2fare from Lesson 7.
A first look at multiple inheritance
A class can have more than one base class. Then the MRO decides the order, and super() follows that order, which can lead to a “sibling” class instead of a parent:
class ShoppingCart:
def __init__(self, owner):
self.owner = owner
self.items = {}
def add_item(self, name, price, quantity=1):
self.items[name] = (price, quantity)
def total(self):
return sum(price * quantity for price, quantity in self.items.values())
def __repr__(self):
return f"{type(self).__name__}({self.owner!r})"
class MemberCart(ShoppingCart):
discount = 10
def total(self):
return super().total() * (100 - self.discount) / 100
class GiftWrap:
def total(self):
return super().total() + 2.0 # add a 2.00 gift wrap fee
class GiftMemberCart(GiftWrap, MemberCart):
pass
cart = GiftMemberCart("Amna")
cart.add_item("pen", 1.5, 4)
cart.add_item("notebook", 3.0)
print([cls.__name__ for cls in GiftMemberCart.__mro__])
print(cart.total())
['GiftMemberCart', 'GiftWrap', 'MemberCart', 'ShoppingCart', 'object']
10.1
- The MRO goes left to right:
GiftWrapbeforeMemberCart. In simple cases the tutorial calls it “depth-first, left-to-right”, but the real rule is “slightly more complex” and putsobjectlast. GiftWraphas no base class exceptobject, yet itssuper().total()reachedMemberCart.total(), the next class in the MRO. That gave 8.1 + 2.0 = 10.1.
Multiple inheritance is easy to get wrong, so keep it for small add-on classes like GiftWrap. Lesson 43 shows another way to combine classes, composition.
Try it yourself
Exercise 1: A sale product
Write a Product class with name, price and a label() method that returns text like "pen: 1.50". Then write SaleProduct(Product) that also takes percent_off, uses super().__init__(), and overrides label() to add " (25% off)" to the parent’s label with super().label().
Exercise 2: Fix the savings account
This code fails. Find the problem and fix it, then add 5% interest to a deposit of 1000:
class Account:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
def deposit(self, amount):
self.balance += amount
class SavingsAccount(Account):
def __init__(self, owner, rate):
self.rate = rate
def add_interest(self):
self.deposit(self.balance * self.rate / 100)
savings = SavingsAccount("Amna", 5)
savings.deposit(1000)
Traceback (most recent call last):
File "/home/learner/python-course/w39/exercise2_broken.py", line 19, in <module>
savings.deposit(1000)
~~~~~~~~~~~~~~~^^^^^^
File "/home/learner/python-course/w39/exercise2_broken.py", line 7, in deposit
self.balance += amount
^^^^^^^^^^^^
AttributeError: 'SavingsAccount' object has no attribute 'balance'
Exercise 3: Predict the output
EBook inherits from DigitalProduct, which inherits from Product. Predict the result of isinstance(EBook(), Product), isinstance(Product(), DigitalProduct), issubclass(EBook, Product), type(EBook()) == DigitalProduct and the MRO of EBook. Then run it.
Solutions
Solution 1
class Product:
def __init__(self, name, price):
self.name = name
self.price = price
def label(self):
return f"{self.name}: {self.price:.2f}"
class SaleProduct(Product):
def __init__(self, name, price, percent_off):
super().__init__(name, price)
self.percent_off = percent_off
def label(self):
return super().label() + f" ({self.percent_off}% off)"
for item in (Product("pen", 1.5), SaleProduct("bag", 20.0, 25)):
print(item.label())
pen: 1.50
bag: 20.00 (25% off)
super().label() builds the normal label, and the override only adds the sale text.
Solution 2
class Account:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
def deposit(self, amount):
self.balance += amount
class SavingsAccount(Account):
def __init__(self, owner, rate):
super().__init__(owner)
self.rate = rate
def add_interest(self):
self.deposit(self.balance * self.rate / 100)
savings = SavingsAccount("Amna", 5)
savings.deposit(1000)
savings.add_interest()
print(savings.owner, savings.balance)
Amna 1050.0
SavingsAccount.__init__ never called the parent’s __init__, so balance did not exist. super().__init__(owner) fixes it: 1000 plus 5% is 1050.0.
Solution 3
class Product:
pass
class DigitalProduct(Product):
pass
class EBook(DigitalProduct):
pass
book = EBook()
print(isinstance(book, Product))
print(isinstance(Product(), DigitalProduct))
print(issubclass(EBook, Product))
print(type(book) == DigitalProduct)
print([cls.__name__ for cls in EBook.__mro__])
True
False
True
False
['EBook', 'DigitalProduct', 'Product', 'object']
An e-book is a product, but a plain product is not a digital product, and type() only gives the exact class.
Common mistakes
- Forgetting
super().__init__(). The parent’s attributes are never created:AttributeError: 'MemberCart' object has no attribute 'items'(see the example above). - Passing
selftosuper().__init__().super()already passesself, sosuper().__init__(self, owner)givesTypeError: ShoppingCart.__init__() takes 2 positional arguments but 3 were given. - Writing
superwithout brackets.super.total()givesAttributeError: type object 'super' has no attribute 'total'. It must besuper().total(). - Silent mistakes in an override. Without
return,super().total() * 0.9makestotal()returnNone. With a typo likedef totl(self):, nothing is overridden and the member pays the full 6.0 instead of 5.4. Neither gives an error, so test your results. - Listing a base class before its own subclass.
class GiftCart(ShoppingCart, MemberCart):fails withTypeError: Cannot create a consistent method resolution order (MRO) for bases ShoppingCart, MemberCart. Put the more specific class first, or simply inherit fromMemberCart.
Frequently asked questions
What does super() do in Python?
super() gives access to methods of the next class in the method resolution order, which in simple inheritance is the parent class. You use it in an overriding method, such as super().total(), to run the parent’s version and then add to it, and in __init__ as super().__init__(...).
What is the difference between overriding and overloading in Python?
Overriding means a subclass defines a method with the same name as its parent, and the subclass version is used. Python has no Java-style overloading: if you write two methods with the same name in one class, the second simply replaces the first, and calling the first form gives a TypeError about a missing argument. Use default values or *args from Lesson 23 instead.
Does Python support multiple inheritance?
Yes. Write several base classes, as in class GiftMemberCart(GiftWrap, MemberCart):. Python searches them in the order shown by __mro__, and super() follows that order. Keep it simple and avoid deep or tangled class trees.
Summary
class Child(Parent):makes a subclass that inherits all of the parent’s methods and attributes.- A subclass can add new methods and override existing ones by using the same name.
super().method()runs the parent’s version so you can extend it; callsuper().__init__(...)in a subclass__init__.- Python finds methods in the order of
__mro__, so a parent method can call a child’s override throughself. - Use
isinstance()andissubclass()for type checks: a subclass object also counts as an object of its base class.
Next lesson
Next: Lesson 41, Python Dunder Methods: Make Your Objects Work Like Built-ins.
Sources
- Classes: Inheritance and Multiple Inheritance (Python tutorial)
- Built-in functions: super(), isinstance() and issubclass() (Python docs)
- Python downloads page (python.org)





