Class inheritance in Python (P1)
Class inheritance in Python (P1) Picture 1
I, Introduction
Classes, along with objects, are the core components of Python. Classes provide a way to organize attributes (data) and methods (behaviors). A very important concept of OOP (Object Oriented Programming) is class inheritance. Class inheritance allows us to create a class that "inherits" all the features of one or more parent classes, modify those features, and add methods and attributes. In this article, we will explore this concept in Python.
II, How to inherit a class
The syntax to inherit a class as a parent class is as follows:
class Parent:
pass
class Child(Parent):
pass
The parent class(es) are defined in () after the child class name.
To check what the parent class(es) of a class are, we use the .__bases__ syntax. The statement will return a tuple containing the parent class(es) of . For the Child class above, the above syntax will return:
Oh so object is the parent of parents. Since Python is an OO(Object Oriented) language, everything in Python is an object except control flow. And object is the base class of all objects in Python. An example to see this is:
III. Ways to extend classes through inheritance
This is the parent class we will use in the three sections below:
1. Add new method(s):
The output will be:
2. Redefine, edit existing method(s) of parent class(es)
The output will be:
3. Add new attribute(s)
I will explain the concept of super() later. You can understand that super() in the current context is to call the previous version — that is, the Animal class. In the example above, it is to pass to the init of the Animal class two attributes, age and gender, as defined by it.
Output:
As you can see polar_bar has all two attributes of Animal which are age, gender, and fur_color attribute which is newly added to Bear class.
IV. Relationship between child and parent classes
The "inheritance" between child and base class(es) will create a "blood" relationship between the 2.
Example checking polar_bear instance type:
Therefore, a piece of code that works with an instance of a parent class should work with an instance of a child class.
V. Conclusion
In this part, I have introduced the basic properties of class - a core feature of Python. I hope this article can help you supplement your knowledge and apply it in your work. In the next part, I will talk about more advanced features of class that not all experienced Python developers know well. We look forward to your support!
You should read it
- Storage class in C / C ++
- Class selector in CSS
- Pseudo-Class in CSS
- Class (Class) in C #
- How to Crash a Class in College
- Storage class in C programming
- Interface in C ++ (Abstract class)
- How To Make The Best Class Assignments?
- How to Write a Class in Python
- Contructor and Destructor in C ++
- Learn Class and Object in Python
- Class member functions in C ++