Classes like a pro: Python Inheritance Tutorial
No question Python is a strong language: with a few lines of code, you can tackle large issues. This is feasible because of abstraction, the capacity to express complicated data. We have begun working on this issue with classes, an excellent method to represent sophisticated data. However, today we are going to proceed one step farther. In this Python Inheritance Tutorial, we are going to learn how you may associate classes with one another such that they share behavior. By now everything could appear unclear, but read now and everything will become obvious.
As you can see, we define three separate entities. However, if you look at the colors, you will see that we can access the attributes from
With this in mind, you can quickly model our famous problem.
This code has a problem. When we instantiate a
This, however, adds some caveats. What if
In case it isn’t clear, the line that calls the super constructor is
Now, take your abstract classes one step further. You can use them to create a template. For example, you can say “I want your class to have at least these methods” with an abstract class. Simply write all the methods in an abstract class, then have other developers extend it. This can be important when you are writing drivers that will control peripheral or streams. You want to be able to call all the functions you need on all the drivers.
Learn to use abstract classes even if you are developing alone. They make your code easier to maintain and extend.
This is handy, especially if you are working with abstract classes. This way you can ensure that you are instantiating an object that is inheriting from the right abstract class, thus having all the methods you need.
Table of Contents about Classes like a pro: Python Inheritance Tutorial
Here’s what we are going to cover today:- Python Inheritance in Simple Terms
- The code of Python Inheritance
- The benefits of Inheritance
- Wrapping it up
Read More: Creating and Testing SDN Software with GNS3
Python Inheritance in Simple Terms[ps2id id='Python Inheritance in Simple Terms' target=''/]
Python Inheritance has profound applications despite its ease of use. You must, however, have a rudimentary understanding of Python classes (if you don't, here's a quick tutorial). Assume you wish to represent people in your system. Assume you want your program to interact with pupils in a school. You may create a Person class that has all of the necessary information, such as name, surname, and home address. In contrast, a school will contain both students and teachers. As a consequence, you should represent two separate entities: Student and Teacher. The student will know about the courses he is taking, and the teacher will know about the courses he is teaching. To spice things up, assume we also need to provide the instructor's salary information, which we don't required on the Student. We also need basic information on both the Student and the Teacher, so why repeat it? After all, both a pupil and a teacher are individuals. This is where inheritance comes into play, as well as the definition. Inheritance enables one class to obtain (inherit) the methods and attributes of another. You may use parent properties and methods on the objects of this child class by instantiating them. Some Python Inheritance Terminology: As you can see, the premise is straightforward. However, in order to fully comprehend it, you must be familiar with inheritance jargon. After all, this is an easy task.- The kid class (or subclass) is the one that inherits properties and methods from the parent class.
- Instead, the parent class (or superclass) is the one that provides characteristics and methods to the child class.
- As observed from the child class, the super constructor is the constructor of the parent class.
- Extending a class involves the creation of a child class that inherits from it.
A visual example
The best way to make the point in this Python Inheritance Tutorial is with a visual example. Remember the Person-Student-Teacher problem we just faced in the introduction, here’s what the logic behind will look like.Person
in both Student
and Teacher
, the blue ones. We didn’t define them either in Student
nor Teacher
, they took them from Person.
The code of Python Inheritance[ps2id id='The code of Python Inheritance' target=''/]
Getting our feet wet
We should start with the simplest possible inheritance: a class that passively inherit from another. In this case, we simply access methods and attributes from the superclass, and nothing more than that. The best example for that is, indeed, our Person-Student-Teacher problem.To define that a class inherits from another, write the parent class name in brackets in the child class declaration.In other words, write something like that:
def ChildClass(ParentClass):
# Child class code...
class Person:
def __init__(self, name, surname, address):
self.name = name
self.surname = surname
self.address = address
class Student(Person):
followed_courses = []
def __init__(self):
pass
class Teacher(Person):
teaching_in_courses = []
salary_info =
def __init__(self):
pass
Student
or Teacher
object, we don’t call the super constructor. Instead, we simply call Student
and Teacher
constructors, and they don’t do anything. We will solve this later on, don’t worry!
Multiple Inheritance
Any modern language will have classes and Inheritance. However, Python goes further with Multiple Inheritance: not all languages have it. This makes Python Inheritance more powerful and even a little bit mind-blowing in some cases.Multiple Inheritance happens when a child class has two or more parent classes.The uses for this approach are rare, but in some very dire circumstances, this feature is going to save you. In this example, we could model a new class
Employee
with salary information, and have the Teacher
inherit from both Person
and Employee
. This is possible and will work like a charm.
However, it is not the best design choice. Since each employee must be a person (not hiring robots so far!), and each teacher must be an employee, the correct model would be Employee
that inherits from Person
and Teacher
that inherits from Employee
. In this case, however, we wouldn’t have multiple inheritances. In order to have that, a child class must inherit from two direct parents at the same time.
Writing a relationship of multiple inheritance is as easy as adding a comma.
class Teacher(Person, Employee):
# The code goes here
Person
and Employee
define the same attributes? They shouldn’t, otherwise, we have the risk of shadowing (hiding) some of them. Nonetheless, this is advanced programming and we don’t have to worry about it. With practice and experience, you will learn how to implement multiple inheritance in the right way.
This is.. super!
Now it is time to introduce our super-awesome keyword:super
. Like self
allows us to access methods and attributes of this object, super
allows us to do that from our superclass.
However, it is a little bit different from self
. In fact, super
is a function and it wants to know the desired parent class and the object from which to extract methods and attributes. It needs the parent class because we might have multiple parents, so it needs to know what is the one we want to access the methods of. And, of course, it needs the object because it needs to know what is the child from which to extrapolate the parent. In many cases, this reference will point to self
.
Thus, we can write this code so that the Student
class calls the __init__()
from Person
.
class Person:
def __init__(self, name, surname, address):
self.name = name
self.surname = surname
self.address = address
class Student(Person):
def __init__(self, name, surname, address followed_courses):
super(Person, self).__init__(name, surname, address)
self.followed_courses = followed_courses
super(Person, self).__init__(name, surname, address)
.
Abstract Classes
An abstract class that does not allow the creation of objects directly. Instead, it must be extended by some child class. While some programming languages have a way of saying “Okay, this class is abstract”, Python does not do that. If we want to achieve this, we need to make it impossible to instantiate the class. To do that, we simply raise aNotImplementedError
in the constructor.
For example, in our system, we might want to have Students and Teachers, but no instance of Person
. Thus, instead of having the constructor do something, we can write it like this.
class Person:
name = ""
surname = ""
address = ""
def __init__(self, name, surname, address):
raise NotImplementedError()
Checking the parent classes
Python offers two awesome functions to verify inheritance and classes in general:type()
and isinstance()
. They behave in two different ways, making them unique for our code.
type()
returns the type of object, that is: its class. It does not consider any superclass.- Instead,
isinstance()
compares an object with a class and returns true if the object is an instance of this class, or subclass.
>>> type(Person('John', 'Doe', 'Temple Bar')) == type(Student('John', 'Doe', 'Temple Bar', []))
false
>>> isinstance(Student('John', 'Doe', 'Temple Bar', []), Person)
true
Read More: Creating and Testing SDN Software with GNS3
The benefits of Inheritance[ps2id id='The benefits of Inheritance' target=''/]
This Python Inheritance Tutorial requires more than just an understanding of inheritance. We also need to grasp what the true benefits of using it are. They are all linked to the scalability and maintenance of your code. Take a look at the bullet points below.- Instead than repeatedly replicating the same data, centralize the data structure definition.
- Divide your code into smaller modules (each subclass) to make it simpler to understand and change, since you only need to notify one component.
- More accurate representation of real-world entities (like Student and Teacher)
- By segmenting your code, you can keep it in smaller, more human-sized files.
Comments
Post a Comment