Python object oriented programming 03: class inheritance and its derived terms

Posted by syd on Sat, 04 Dec 2021 23:15:44 +0100

Chapter 38 of the official Python column, students stop. Don't miss this article starting from 0!

In the previous article, the School Committee showed and shared object-oriented programming and Deep understanding of class structure Finally, I mentioned inheritance a little.

This time we will explain the terms of inheritance and inheritance derivation together

Python supports single inheritance and multiple inheritance

Taking advantage of the deep impression, the school committee took the code of the previous article and slightly modified it:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time: 11:58 PM, November 15, 2021
# @Author : LeiXueWei
# @CSDN/Juejin/Wechat: Thunder Science Committee
# @XueWeiTag: CodingDemo
# @File : __init__.py.py
# @Project : hello

"""
Here is a programmer class definition
"""


class Programmer():
    def code(self):
        print("life is short, why not python?")

"""
The following is a student class definition
"""


class Student(object):
    """Here is a student class definition"""

    def __init__(self, name):
        self.name = name

    def get_name(self):
        return self.name

    def set_name(self, name):
        self.name = name

    def study(self):
        print(f"{self.name} : study hard and make progress every day!")


# Multiple inheritance (parent 1, parent 2) can have more parent classes
class PrimarySchoolStudent(Student, Programmer):
    pass


print("*" * 16)
xiaopengyou = PrimarySchoolStudent("A pupil (a fan of the school committee)")
xiaopengyou.study()
xiaopengyou.code()

print("Base class of class:", PrimarySchoolStudent.__bases__)

Through multi inheritance, we easily created a class PrimarySchoolStudent, which is both a student and a programmer!

class PrimarySchoolStudent(Student, Programmer)

This is the result of the run:

As you can see, it is very easy to create a new class PrimarySchoolStudent with two class behaviors and properties.

The following paragraph adds that Python provides a tool function 'issubclass' to facilitate us to identify the relationship between the class in hand and a class.

'isinstance' also helps us identify the relationship between an object and a class.

# Is it a subclass of which class the object is derived from
print("PrimarySchoolStudent yes Programmer Subclass of?", issubclass(PrimarySchoolStudent, Programmer))
print("PrimarySchoolStudent yes Student Subclass of?", issubclass(PrimarySchoolStudent, Student))
print("Student yes Programmer Subclass of?", issubclass(Student, Programmer))

# Determine which class the object is created from
print("xiaopengyou yes PrimarySchoolStudent Examples of?", isinstance(xiaopengyou, PrimarySchoolStudent))
print("xiaopengyou yes Programmer Examples of?", isinstance(xiaopengyou, Programmer))
print("xiaopengyou yes Student Examples of?", isinstance(xiaopengyou, Student))
print("xiaopengyou yes dict Examples of?", isinstance(xiaopengyou, dict))

Readers try to copy and run this code to deepen their impression.

Sometimes a child is unwilling to inherit his father's will, and a child can choose to override - Overriding

For example, this class of primary school students wants to rewrite the study function to play games.

In object-oriented programming, this is allowed and legal! (unless Java sets the final attribute, which is outside the scope of this article)

Then, let me revise:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time: 11:58 PM, November 15, 2021
# @Author : LeiXueWei
# @CSDN/Juejin/Wechat: Thunder Science Committee
# @XueWeiTag: CodingDemo
# @File : __init__.py.py
# @Project : hello
"""
Here is a programmer class definition
"""


class Programmer():
    def code(self):
        print("life is short, why not python?")


"""
The following is a student class definition
"""


class Student(object):
    """Here is a student class definition"""

    def __init__(self, name):
        self.name = name

    def get_name(self):
        return self.name

    def set_name(self, name):
        self.name = name

    def study(self):
        print(f"{self.name} : study hard and make progress every day!")


class PrimarySchoolStudent(Student, Programmer):
    def study(self):
        print(f"{self.name} : Have fun playing games!")


print("*" * 16)
xiaopengyou = PrimarySchoolStudent("A pupil (a fan of the school committee)")
xiaopengyou.study() 
xiaopengyou.code()

Again, inheritance allows subclasses to directly own the functions and data properties of the parent class, which can be accessed and used directly.

Then, this change is only one more function than the first paragraph of the previous code. The school committee redefined a study function in PrimarySchoolStudent.

So the function of the subclass covers the function of the parent class (the parent class is also masked, he never knows this!) note that the function with the same name must be said!

OK, let's look at the following running results:

summary

Class inheritance produces parent-child inheritance, but allows differences between parents and children. Speaking of this today.

The school committee has written Java for more than ten years, but the Python tutorial is very pragmatic. If you have any problems with basic programming, please check the relevant articles.

If you like Python, please pay attention to the school committee Python foundation column or Introduction to Python to master the big column

Continuous learning and continuous development, I'm Lei Xuewei!
Programming is very interesting. The key is to understand the technology thoroughly.
Welcome to wechat, like and support collection!

Topics: Python OOP