Python InheritanceGet Certified
What Is Inheritance?
Inheritance lets one class reuse and extend the code of another class. Think of how a pickup truck and a sedan are both kinds of vehicle: they share wheels, an engine, and a way to start, but each also has features of its own. In Python you write the shared parts once in a parent class, and then create child classes that automatically receive everything the parent has. A child class can add new attributes and methods, or change the behavior it inherited. This saves you from copying code, keeps related classes organized, and makes a program easier to change, because a fix in the parent reaches every child at once.
- Parent class: the class that is inherited from. It is also called the base class or superclass.
- Child class: the class that inherits. It is also called the derived class or subclass.
- “Is-a” relationship: a
Caris aVehicle, and aStudentis aPerson. - Reuse: a child gets all the attributes and methods of its parent without rewriting them.
- Overriding: a child can replace a method of its parent with its own version.
super(): a way for the child to call the parent’s code.
Creating a Child Class
To create a child class, write the name of the parent class in parentheses after the name of the new class: class Car(Vehicle):. That single change gives Car every attribute and method that Vehicle defines. If the child needs nothing extra yet, its body can be just pass, and it still works as a complete class. When you create an object from the child class, Python looks for each method in the child first, and then in the parent, so the parent’s methods are found automatically. If the child has no __init__ of its own, the parent’s __init__ is used to build the object.
Try It: A Child Class That Inherits Everything
Click Test My Code. Then add a second child class named Truck(Vehicle) with pass and create a truck object.
Vehicle class with an initializer and two methods, and an empty Car class that inherits from it. It creates a car, calls the inherited methods, and uses isinstance() and issubclass() to confirm the relationship between the two classes.class Vehicle:
def __init__(self, make, model):
self.make = make
self.model = model
def describe(self):
return f"{self.make} {self.model}"
def start(self):
return f"The {self.model} is starting"
class Car(Vehicle):
pass
car = Car("Ford", "Mustang")
print(car.describe())
print(car.start())
print(isinstance(car, Car), isinstance(car, Vehicle))
print(issubclass(Car, Vehicle))Vehicle is the parent, or base, class. It holds the code that all kinds of vehicles will share.__init__ runs whenever a new object is created. It receives the make and the model of the vehicle.describe() will be available to every child class.start() is also inherited by the child classes.Vehicle, makes Car a child class. It inherits all the attributes and methods of Vehicle.pass means that Car adds nothing of its own yet. It is still a complete class.Car has no __init__, so Python uses the one that it inherited from Vehicle. The make is "Ford" and the model is "Mustang".describe() is not defined in Car, so Python finds it in Vehicle. The output is Ford Mustang.The Mustang is starting.isinstance() asks whether an object belongs to a class or to one of its parents. The car is a Car and also a Vehicle. The output is True True.issubclass() asks whether a class inherits from another class. The output is True.Adding New Attributes with super().__init__()
A child class usually needs more than its parent has, for example a student has a school and a grade point average on top of a name and a city. When you write an __init__ in the child class, it replaces the parent’s __init__, so the parent’s attributes would not be created unless you ask for them. The built-in super() function solves this: it gives you access to the parent class, so super().__init__(...) runs the parent’s initializer for you. The usual pattern is to call it first, and then to set the attributes that belong only to the child.
Try It: A Student Is a Person
Click Test My Code. Comment out the super().__init__ line, run it again, and read the error.
Person class with a name, a city, and an introduce() method. The Student child class adds a school and a grade point average, calls the parent initializer with super(), and adds a study() method. The program creates one student and uses methods and attributes from both classes.class Person:
def __init__(self, name, city):
self.name = name
self.city = city
def introduce(self):
return f"Hi, I'm {self.name} from {self.city}."
class Student(Person):
def __init__(self, name, city, school, gpa):
super().__init__(name, city)
self.school = school
self.gpa = gpa
def study(self):
return f"{self.name} is studying at {self.school}."
emma = Student("Emma Davis", "Chicago", "Northwestern University", 3.9)
print(emma.introduce())
print(emma.study())
print(emma.gpa, emma.city)Person holds what every person has: a name and a city.introduce() will be available to every kind of person, including students.I'm is fine inside double quotes.Student(Person) makes Student a child of Person.__init__ replaces the parent’s one. It accepts two extra values, the school and the grade point average.super().__init__(name, city) runs Person.__init__, which sets self.name and self.city. Without this line, those two attributes would not exist.study() exists only in Student, not in Person.self.name, which was set by the parent, and self.school, which was set by the child.introduce() comes from Person. The output is Hi, I'm Emma Davis from Chicago.Emma Davis is studying at Northwestern University.3.9 Chicago.Overriding Methods and Extending Them with super()
Sometimes a child class needs to behave differently from its parent. To change an inherited method, you define a method with the same name in the child class. This is called overriding, and Python always chooses the child’s version for objects of the child class. The parent’s version is not lost, because inside the child’s method you can call super().method_name() to run the parent’s code and then build on its result. This lets a child extend a behavior instead of rewriting it from scratch.
Try It: Employees and Managers
Click Test My Code. Change the manager’s bonus to 0 and check that both people are paid the same way.
Employee class whose annual_pay() returns the salary. A Manager child class adds a bonus and overrides annual_pay() to add the bonus to the pay calculated by the parent. A loop prints the pay of one employee and one manager.class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
def annual_pay(self):
return self.salary
class Manager(Employee):
def __init__(self, name, salary, bonus):
super().__init__(name, salary)
self.bonus = bonus
def annual_pay(self):
return super().annual_pay() + self.bonus
staff = [Employee("Tyler Brooks", 52000), Manager("Jennifer Ramirez", 78000, 12000)]
for person in staff:
print(f"{person.name}: ${person.annual_pay():,}")Employee describes what every employee has in common.annual_pay() calculates what an employee earns in a year.Manager inherits from Employee.super().__init__(name, salary) sets the name and the salary in the same way as for any employee.Employee, so it overrides it for managers.super().annual_pay() runs the parent’s version, which returns the salary. The bonus is then added to it.person is one object on each repetition. The loop does not need to know which kind of object it has.annual_pay() for each object. The comma in :, adds a thousands separator. The output is Tyler Brooks: $52,000 and Jennifer Ramirez: $90,000.Checking Relationships: isinstance(), issubclass(), and the MRO
Python gives you several tools to ask how objects and classes are related. The function isinstance(obj, Class) is true when the object belongs to the class or to any of its parents, which is exactly what the “is-a” idea means. The function issubclass(A, B) asks the same question about two classes. By contrast, type(obj) returns only the exact class of the object, so comparing it with == ignores inheritance. Every class also keeps a record of its ancestors: __bases__ lists its direct parents, and __mro__, the method resolution order, lists every class in the order in which Python searches for a method.
isinstance(obj, Class)is true for the class of the object and for all of its ancestors.issubclass(Child, Parent)is true when the child inherits from the parent, directly or indirectly.type(obj) == Classis true only for the exact class, so it is stricter thanisinstance().Class.__mro__shows the search order, and the last class is alwaysobject.- Every class in Python inherits from the built-in class
object, even when you do not write it.
Try It: A Family Tree of Classes
Click Test My Code. Predict each line before you read the output, especially the one that compares exact types.
Animal, Dog, and Puppy, and creates a puppy. It tests the puppy with isinstance(), tests the classes with issubclass(), shows the exact type, compares exact types, and prints the method resolution order and the direct parent of Dog.class Animal:
pass
class Dog(Animal):
pass
class Puppy(Dog):
pass
rex = Puppy()
print(isinstance(rex, Puppy), isinstance(rex, Dog), isinstance(rex, Animal))
print(issubclass(Puppy, Animal), issubclass(Animal, Puppy))
print(type(rex).__name__)
print(type(rex) == Dog)
print([cls.__name__ for cls in Puppy.__mro__])
print(Dog.__bases__[0].__name__)Animal is the top of this small family. It inherits only from object.pass keeps the class empty. That is enough to demonstrate the relationships.Dog inherits from Animal.pass keeps the class empty.Puppy inherits from Dog, and so indirectly from Animal.rex refers to a new Puppy object.Puppy, a Dog, and an Animal. The output is True True True.Puppy inherits from Animal, but Animal does not inherit from Puppy. The output is True False.type(rex) is the exact class, and __name__ gives its name as text. The output is Puppy.type(rex) == Dog is false, because the exact type is Puppy. This is why isinstance() is usually the better test. The output is False.__mro__ lists the classes in the order in which Python searches them, ending with object. The output is ['Puppy', 'Dog', 'Animal', 'object'].Dog.__bases__ is a tuple of the direct parents. Its first item is Animal. The output is Animal.Multi-Level Inheritance
Inheritance can go several levels deep: a class can inherit from a class that itself inherits from another class, forming a chain. An electric car, for example, is a car, and a car is a vehicle, so an ElectricCar receives the code of both Car and Vehicle. Each level adds something new, and each initializer calls super().__init__() to pass the shared values up the chain. When you create an object of the lowest class, the initializers run from the bottom up to the top, and they finish in the opposite order, so the parent’s work is always done first.
Try It: A Chain of Initializers
Click Test My Code. Watch the order of the three messages carefully, because it shows how the initializers call each other.
Vehicle, Car, and ElectricCar. Each initializer prints a message and passes its shared values up with super(). Creating one electric car shows the order in which the messages appear, and the final line proves that the object has the attributes of all three classes.class Vehicle:
def __init__(self, brand):
self.brand = brand
print("Vehicle created")
class Car(Vehicle):
def __init__(self, brand, doors):
super().__init__(brand)
self.doors = doors
print("Car created")
class ElectricCar(Car):
def __init__(self, brand, doors, range_miles):
super().__init__(brand, doors)
self.range_miles = range_miles
print("ElectricCar created")
tesla = ElectricCar("Tesla", 4, 358)
print(tesla.brand, tesla.doors, tesla.range_miles)Vehicle is the parent of Car, and the grandparent of ElectricCar.Vehicle part of an object has been built. It will be the first message that you see.Car inherits from Vehicle.super().__init__(brand) runs the Vehicle initializer, which sets the brand and prints its message.ElectricCar inherits from Car.super().__init__(brand, doors) runs the Car initializer, which in turn runs the Vehicle initializer.Vehicle created, Car created, and ElectricCar created, which shows that the top of the chain finishes first.Vehicle, the doors from Car, and the range from ElectricCar. The output is Tesla 4 358.Multiple Inheritance and the MRO
Python also allows a class to have more than one parent: class Triathlete(Swimmer, Runner):. The child receives the methods of every parent, which is useful when a class combines separate abilities. If two parents define a method with the same name, Python needs a rule to choose, and the rule is the method resolution order. It searches the child first, and then the parents from left to right in the order they are written, and each class is searched only once. Multiple inheritance is powerful but can make code hard to follow, so use it sparingly and keep the parent classes small and independent.
Try It: Combining Two Parents
Click Test My Code. Swap the order of the parents to (Runner, Swimmer) and see how the first result changes.
Swimmer and a Runner. Both have a move() method, and the runner also has sprint(). The Triathlete class inherits from both. The program shows which move() wins, calls the method that only one parent has, and prints the order in which Python searches the classes.class Swimmer:
def move(self):
return "swims"
class Runner:
def move(self):
return "runs"
def sprint(self):
return "sprints"
class Triathlete(Swimmer, Runner):
pass
athlete = Triathlete()
print(athlete.move())
print(athlete.sprint())
print([cls.__name__ for cls in Triathlete.__mro__])Swimmer is a small class with a single ability.move() describes how a swimmer moves."swims".Runner is another small class.move()."runs".sprint() exists in Runner but not in Swimmer."sprints".Triathlete inherits from both of them.athlete refers to a new Triathlete object.move(). Python searches the parents from left to right, so Swimmer comes first. The output is swims.Runner defines sprint(), so Python finds it there. The output is sprints.['Triathlete', 'Swimmer', 'Runner', 'object']. This is the order in which Python looks for a method.Inheritance vs Composition
Inheritance is not always the right tool. It fits an “is-a” relationship, such as a Car that is a Vehicle. When one object merely has another object, as a truck has an engine, the better design is composition: the truck stores an Engine object in an attribute and calls its methods. A truck is not a kind of engine, so inheriting from Engine would be wrong and confusing. A helpful test is to say the sentence aloud: “a truck is an engine” sounds odd, while “a truck has an engine” sounds right, so composition is the better choice.
- Inheritance models “is-a”: a
Studentis aPerson. - Composition models “has-a”: a
Truckhas anEngine, and aSchoolhas manyStudentobjects. - Composition is more flexible, because the parts can be replaced without changing the class hierarchy.
- Prefer shallow hierarchies, because deep chains of parents are hard to understand and change.
Try It: A Truck Has an Engine
Click Test My Code. Change the horsepower to 300 and see where the value is used.
Engine class and a Truck class that stores an engine object inside itself instead of inheriting from it. The truck’s start() method asks its engine to start, and the last line shows that a truck is not an instance of Engine.class Engine:
def __init__(self, horsepower):
self.horsepower = horsepower
def start(self):
return "Engine roars to life"
class Truck:
def __init__(self, model, horsepower):
self.model = model
self.engine = Engine(horsepower)
def start(self):
return f"{self.model}: {self.engine.start()}"
pickup = Truck("Ranger", 400)
print(pickup.start())
print(pickup.engine.horsepower)
print(isinstance(pickup, Engine))Engine describes one part of a vehicle.Truck does not inherit from anything. There are no parentheses after its name.Engine object and keeps it in the attribute self.engine. This is composition.start() method."Ranger" and an engine of 400 horsepower.Ranger: Engine roars to life.400.False.Base Classes That Require Overriding
Sometimes a parent class describes what its children must be able to do, without knowing how each child does it. A Shape class, for instance, can promise an area() method, but the formula depends on whether the shape is a rectangle or a circle. A common way to express this promise is to make the parent’s method raise NotImplementedError, which tells every child class: “you must replace this method”. Children that override the method work normally, and a child that forgets it fails with a clear message. Python’s abc module offers an even stricter tool, abstract base classes, which you can explore later.
Try It: A Shape Family
Click Test My Code. Add an area() method to Circle that returns 3.14 * self.radius ** 2 and watch the last line change.
Shape base class whose area() raises NotImplementedError. Rectangle overrides it, Square inherits from Rectangle and passes its side twice to the parent initializer, and Circle forgets to override it. A loop shows what happens for each one.class Shape:
def area(self):
raise NotImplementedError("Subclasses must implement area()")
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
class Square(Rectangle):
def __init__(self, side):
super().__init__(side, side)
for shape in [Rectangle(3, 4), Square(5), Circle(2)]:
try:
print(type(shape).__name__, shape.area())
except NotImplementedError as error:
print(type(shape).__name__, "->", error)Shape describes what every shape should be able to do.area() is defined here, but only as a promise that children must keep.NotImplementedError with a message. Any child class that does not replace the method will fail with this message.Rectangle inherits from Shape.Circle inherits from Shape but does not provide an area() method.Square inherits from Rectangle, so it also receives area().shape takes each one in turn.area() might fail for some shapes, so it is protected.Rectangle 12 and the square gives Square 25. For the circle, area() comes from Shape and raises NotImplementedError.NotImplementedError that the circle caused.Circle -> Subclasses must implement area().Tip: When you design a family of classes, put the attributes and methods that every child needs in the parent, and keep what is special in the children. Ask yourself whether the sentence “a child is a parent” makes sense. If it does not, use composition instead. Keep the hierarchy shallow: two or three levels are usually plenty.
Using Inheritance with User Input
Inheritance combines well with user input, because a program can read a few answers and then decide which class to create. Classes are ordinary objects in Python, so you can store them in a dictionary and look them up by name, which avoids a long chain of if statements. The object that you create then behaves according to its class, but you can use it in the same way as any other object of the family. Remember that input() returns text, so convert numbers with int() or float() before you pass them to a class.
Try It: Choosing a Pet Class
The Program Input box is already filled with three lines: Buddy, Dog, and 3. Click Run Code straight away, then try cat, and finally a kind that is not in the dictionary, such as parrot.
Pet base class and two children, Dog and Cat, that override the sound() method. A dictionary maps the words dog and cat to their classes. The program reads a name, a kind, and an age, picks the matching class with get(), falling back to Pet, and creates and describes the pet.class Pet:
def __init__(self, name, age):
self.name = name
self.age = age
def sound(self):
return "..."
class Dog(Pet):
def sound(self):
return "Woof"
class Cat(Pet):
def sound(self):
return "Meow"
kinds = {"dog": Dog, "cat": Cat}
name = input("Pet name: ")
kind = input("Dog or cat? ").strip().lower()
age = int(input("Age: "))
pet = kinds.get(kind, Pet)(name, age)
print(f"{pet.name} ({type(pet).__name__}), age {pet.age}, says {pet.sound()}")
print(isinstance(pet, Pet))Pet holds what every pet has in common."...".Dog inherits from Pet, including its initializer."Woof".Cat also inherits from Pet."Meow".Buddy, is stored as text.Dog. strip() removes extra spaces and lower() makes it lowercase, so it becomes dog.3, is converted to an integer.kinds.get(kind, Pet) returns the class Dog, or Pet if the word is not in the dictionary. Adding (name, age) calls the class and creates the object.Buddy (Dog), age 3, says Woof.Pet. The output is True.Try It: A Savings Account
The Program Input box is filled with three lines: Michael Johnson, 1000, and 5. Click Run Code, then try other balances and interest rates.
Account class with a deposit() method, and a SavingsAccount child class that adds an interest rate and an add_interest() method. The method reuses the inherited deposit(). The program reads the details, creates a savings account, deposits $250, adds interest, and prints the balance.class Account:
def __init__(self, owner, balance):
self.owner = owner
self.balance = balance
def deposit(self, amount):
self.balance += amount
class SavingsAccount(Account):
def __init__(self, owner, balance, rate):
super().__init__(owner, balance)
self.rate = rate
def add_interest(self):
self.deposit(self.balance * self.rate / 100)
owner = input("Account owner: ")
balance = float(input("Starting balance: "))
rate = float(input("Interest rate (%): "))
account = SavingsAccount(owner, balance, rate)
account.deposit(250)
account.add_interest()
print(f"{account.owner}'s balance: ${account.balance:,.2f}")Account describes any bank account.deposit() receives an amount of money.+= adds the amount to the balance that is stored in the object.SavingsAccount inherits from Account.super().__init__(owner, balance) sets the owner and the balance.deposit() method, so no new code is needed to change the balance.Michael Johnson, is stored as text.1000, is converted to the float 1000.0.5, is converted to the float 5.0.SavingsAccount object is created from the three answers.deposit() adds 250 and the balance becomes 1250.0.Michael Johnson's balance: $1,312.50.Common Mistakes with Inheritance
Inheritance is easy to start with and surprisingly easy to misuse. Most problems come from forgetting how the parent and the child cooperate, or from choosing inheritance when a simpler design would work better. Some mistakes raise a clear error, such as a missing attribute, while others silently do the wrong thing, such as a method that was meant to override but has a slightly different name. Check the list below when an object does not behave as you expect.
- Forgetting
super().__init__(): when a child defines its own__init__, the parent’s attributes are not created. Later you get anAttributeError. - Wrong arguments to
super().__init__(): passing too few or too many values raises aTypeError. Match the parent’s parameters. - A misspelled method name: a child method called
anual_pay()does not overrideannual_pay(). It just creates a new method, and the parent’s version still runs. - Forgetting the parent in the class line:
class Car:creates an unrelated class. Writeclass Car(Vehicle):. - Using inheritance for “has-a”: a truck is not an engine. Store the engine in an attribute instead.
- Deep or tangled hierarchies: long chains and complicated multiple inheritance are hard to follow. Keep the tree shallow.
- Comparing with
type(obj) == Class: this ignores subclasses. Useisinstance()in most cases. - Changing the meaning of an inherited method: a child should accept the same kinds of arguments and return the same kind of result as the parent, so that it can be used wherever the parent is expected.
Key Takeaways
Inheritance is one of the main tools of object-oriented programming, and with it you can build families of related classes without repeating code. The points below summarize the essentials, and they prepare you for the next lesson on polymorphism and encapsulation, where you will see how objects of different classes can be used in the same way. Keep this list in mind whenever you design a new class that resembles an existing one.
- A child class inherits all the attributes and methods of its parent:
class Child(Parent):. - Use
super().__init__(...)in the child’s initializer to run the parent’s initializer, and then add the child’s own attributes. - A method with the same name in the child overrides the parent’s method, and
super().method()lets the child extend it. isinstance()andissubclass()test “is-a” relationships, and__mro__shows the order in which Python searches for methods.- Inheritance can have several levels, and a class can have several parents, but a shallow and simple hierarchy is easier to understand.
- Use inheritance for “is-a” and composition for “has-a”.
- A base method that raises
NotImplementedErrortells every child that it must provide its own version.
Frequently Asked Questions
The questions below are the ones that students ask most often when they first learn about inheritance in Python. Each answer is short and practical, and each idea is shown in one of the examples above. If you are still unsure, experiment: create a small parent class, derive a child from it, and change one thing at a time to see how the behavior changes.
What is inheritance in Python?
Inheritance is a feature of object-oriented programming in which a child class receives the attributes and methods of a parent class. The child can reuse that code, add new attributes and methods, and override the behavior that it inherited.
How do I make a class inherit from another class in Python?
Write the name of the parent class in parentheses after the name of the child class, for example class Car(Vehicle):. The Car class then has all the attributes and methods of Vehicle.
What does super() do in Python?
The super() function gives a child class access to its parent class. It is most often used as super().__init__(…) to run the parent’s initializer, and as super().method_name() to call the parent’s version of a method that the child has overridden.
What is method overriding in Python?
Method overriding means that a child class defines a method with the same name as a method of its parent. Python then uses the child’s version for objects of the child class. The child can still call the parent’s version with super().
What is the difference between isinstance() and type() in Python?
The isinstance(obj, Class) function is true when the object belongs to the class or to any of its parent classes. Comparing type(obj) == Class is true only for the exact class. For this reason isinstance() is usually the better choice when inheritance is involved.
Does Python support multiple inheritance?
Yes. A class can list several parents, as in class Triathlete(Swimmer, Runner):. Python looks for a method in the child first and then in the parents from left to right, following the method resolution order, which you can see in Class.__mro__.
What is the method resolution order (MRO) in Python?
The method resolution order is the sequence of classes that Python searches when you call a method or read an attribute of an object. It starts with the object’s own class, continues through the parent classes, and ends with the built-in class object. You can print it with Class.__mro__.
When should I use composition instead of inheritance in Python?
Use inheritance for an “is-a” relationship, such as a Student that is a Person. Use composition for a “has-a” relationship, such as a Truck that has an Engine, by storing the other object in an attribute. Composition is more flexible and avoids deep class hierarchies.