Python Class Inheritance Example

Today we will be talking about OOP method of programming. The particular area of our interest would be Inheritance. Before we go any further, let’s talk about basic principles of programming. We know that there is an imperative method (when we use for and while loops), functional (when we operate with functions) or Object Oriented Programming (where we write code using classes).

1. Intro to Classes

We know many data structures that Python has: tuples (which are basically immutable arrays of objects), lists (same as tuples, but they are actually mutable) and dictionaries (which can be represented as hash tables). They are all good, but sometimes you need better tools to implement things you want.
For example, we have a company that has different workers who hold various job positions. We can surely put all data in an array (which would take a long time), dictionary (which would be a better option, but still time-consuming) or we can just create a Class worker with parameters explaining their job positions, work experience, salary, etc. That way, if we want to extract some information or add something new, we would operate with specific Class.
So basically, Classes are structures or, in other words, skeletons of our data which we will eventually fill in. Then another question comes up, “How can we fill the structure?”

2. Intro to Instances

Well, we have an idea what Class is. It’s a structure, showing us with what and how to fill it. If we want to fill it (which we surely do!), we need to create instances. It’s a copy of class that is filled with data.
Let’s look at the example below with workers in a company, shall we?
We are creating a class called worker with parameters name, position, and experience:

class worker(object): 

   def __init__(self,name,position, experience): = name
      self.position = position
      self.experience = experience
   def getName(self):
   def getPosition(self):
      return self.experience
   def getExperience(self):
      return self.experience
   def __str__(self):
     return "%s is %s and has been working here for the past %d years" %(, self.position, self.experience)

Line 1: We are creating the class. The word class means that we tell Python to create a class and the word worker is the name of it! The word object is just a special variable that needs to be included in order to create a new class.

Lines 2-5: We are creating a function by writing def. Then we are using magic method (as known as Dunder) called __init__. The key idea for using it is because we are creating an instance of class firstly.
The word self is the instance of the class worker. This is done so we can insert different data depending upon various circumstances.

Lines 6-11: We are creating functions that return instances of the class. For example, the getPosition method takes an instance of a worker as a parameter and looks up the worker’s job position. Note: we use self to figure out the content (which can be done automatically by Python).
Let’s create John who has worked with the company for 15 years and he is a manager:

Python shell

>>>  first = worker("John", "manager", 15)

Then we will try to retrieve information about him:

Python shell

>>>  first = worker("John", "manager", 15)
>>>  first.getName()
>>>  first.getPosition()
>>>  first.getExperience()
>>> print(first)
John is manager and has been working here for the past 15 years

It works! So what we do here is every time we call methods getName, getPosition or getExperience we receive information about itself.

Lines 12-13: Another magic method is __str__ which defines the behavior of what will happen if we write print(Class name) .
Let’s try to add more workers:

Python shell

>>>  second = worker("Monica", "programmer", 12)
>>>  print(second)
Monica is programmer and has been working here for the past 12 years
>>>  third = worker("Jimmy", "programmer", 2)
>>>  print(third)
Jimmy is programmer and has been working here for the past 12 years
>>>  fourth = worker("Lisa", "manager", 4)
>>>  print(fourth)
Lisa is manager and has been working here for the past 12 years

You are probably asking right now, “Okay, we create classes. It’s fun but wait… What if we have not 4 but 400 people in the company? We can’t create instances all the time and we can’t sort people like that. It’s too complex!” I am glad that you asked! There is another thing called subclasses.

3. Intro to subclasses

Well, maybe we have John and Lisa as managers, Monica and Jimmy as programmers. Let’s create subclasses programming and management. Firstly, let’s see what we can do with the class management:

class management(worker):
   def __init__(self, name, management_skills, experience):
      worker.__init__(self, name, "management", experience)
      self.management_skills = management_skills
   def management_skills(self):
      return self.management_skills

What we want to do here is to specify that all management have position manager. Since we want name, position, and experience to be initialized, we write the line 3.
Let’s see what happen in Python shell when we find differences between worker and management:

Python shell

>>>  example_worker = worker("Alex", "programmer", 1)
>>>  example_management = management("Aleks", "manager", 1)

What we want to check right now is whether one instance is certain class’s instance. We can do it by calling isinstance():

Python shell

>>>  isinstance(example_worker, worker)
>>>  isinstance(example_worker, management)
>>>  isinstance(example_management, worker)
>>>  isinstance(example_management, management)

One thing may seem confusing to you right now, “Why is example_management and worker returns true?”. That’s a very good question! Since management is worker’s subclass, it inherits attributes of it. In other words, worker is a base for management, so every time we check for worker as a second parameter, we get True. But we can only get True while calling for management if we are calling the very same subclass (which is the last line of the code above).

4. Summary

In the example above we saw multiple things:

  • Inheritance: It’s one of the paradigms of OOP. It helps you to write code more efficiently but can be tricky at the beginning.
  • Instances: It’s a copy of class with filled data. Basically, when you want to build a class, you explain what data will be put there, but an instance is a complete class with filled data in it.
  • Magic methods: Those are special methods for operator overloading. A good example of such is __add__ that means +. There are plenty of those, like __sub__, __mul__, __truediv__, __mod__ and many others.
  • Subclasses: They are used when you have data with common attributes. For example, you have a farm with 1000 animals. Most of them have 4 legs, and you want to collect data from those who have fewer than 4 legs (like ducks or something like that). That’s why you would need to use subclasses – to classify multiple arrays of objects in specific arrays with special attributes

5. Instead of conclusion

I hope inheritance seems more logical for you now (if you were struggling with it). In fact, the best way to learn about classes and inheritance is to actually write code. It plays vital role in DRY principle (as known as Don’t Repeat Yourself).
Surely, there is a lot more you need to know in order to advance: encapsulation, polymorphism, static classes, abstract classes, etc.

So here is some homework for you:
Write a program where class of geometric figure (figure) consists of color (color) with the default set as white and method of changing the figure. Its subclasses are oval (oval) and parallelepiped (parallelepiped) which have methods __init__ to set size of objects

Example of how it can be done can be seen below:

class figure():
   color = "white"
   def changecolor(self, newcolor):
      self.color = newcolor

class oval(figure):
   def __init__(self, radius):
      self.radius = radius

class parallelepiped(figure):
   def __init__(self, width, height):
      self.width = width
      self.height = height

f = figure()
o = oval(10)
p = parallelepiped(20,5)

print(o.color, o.radius)
print(p.color, p.width, p.height)

6. Download the source code

This was an example of inheritance.

You can download the full source code of this example here:

Aleksandr Krasnov

Aleksandr is passionate about teaching programming. His main interests are Neural Networks, Python and Web development. Hobbies are game development and translating. For the past year, he has been involved in different international projects as SEO and IT architect.
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments
Back to top button