current position:Home>Python object oriented programming 03: class inheritance and its derived terms

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

2022-01-31 20:01:49 Lei Xuewei

「 This is my participation 11 The fourth of the yuegengwen challenge 15 God , Check out the activity details :2021 One last more challenge

ceremonial Python Column No 38 piece , Classmate, stop , Don't miss this from 0 The beginning of the article !

In the previous article, the Academic Committee showed and shared the structure of object-oriented programming and classes , Finally, a little mention of inheritance .

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

Python Support single inheritance , Multiple inheritance

Take advantage of the deep impression , The school committee took the code of the previous article and made some modifications :

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/11/15 11:58  Afternoon 
# @Author : LeiXueWei
# @CSDN/Juejin/Wechat:  Lei Xuewei 
# @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?")

"""  Here 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 , Day day up !")


class PrimarySchoolStudent(Student, Programmer):
    pass


print("*" * 16)
xiaopengyou = PrimarySchoolStudent(" A pupil ( A fan of the School Committee )")
xiaopengyou.study()
xiaopengyou.code()

print(" Class base class :", PrimarySchoolStudent.__bases__)
 Copy code 

This is the result of the operation :

 Screenshot  2021-11-17  Afternoon 11.34.37.png

You can see , It's easy to create a new class with two class behaviors and properties PrimarySchoolStudent.

The following paragraph adds ,Python Tool functions are provided ‘issubclass’ It is convenient for us to identify the class in hand Follow The relationship of a class .

‘isinstance’ It 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  Example  ?", isinstance(xiaopengyou, PrimarySchoolStudent))
print("xiaopengyou  yes  Programmer  Example?  ?", isinstance(xiaopengyou, Programmer))
print("xiaopengyou  yes  Student  Example?  ?", isinstance(xiaopengyou, Student))
print("xiaopengyou  yes  dict  Example?  ?", isinstance(xiaopengyou, dict))
 Copy code 

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

Sometimes a son doesn't want to follow his father's wishes , Subclasses can choose to override - Overriding

For example, this class of primary school students , You want it study The function is rewritten to play a game .

In object oriented programming , This is allowed and legal !( Unless like Java Set up final attribute , This is outside the scope of this article )

that , I'll change it :

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/11/15 11:58  Afternoon 
# @Author : LeiXueWei
# @CSDN/Juejin/Wechat:  Lei Xuewei 
# @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?")


"""  Here 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 , Day day up !")


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()
 Copy code 

Again , Inheritance allows subclasses to directly own the functions and data properties of the parent class , You can directly access and use .

Then this change is just one more function than the first paragraph of the previous code , School Committee in PrimarySchoolStudent, Redefined a study function .

therefore The function of the subclass overrides the function of the parent class ,( The parent class is also masked , He never knew about it !) Note that you must say the function with the same name !

Okay , Look at the running results below :

 Screenshot  2021-11-18  In the morning 12.25.30.png

summary

Class inheritance produces parent-child inheritance , But father and son are allowed to differ . Speaking of this today .

The school committee has written for more than ten years Java 了 , But this set of writing Python The tutorial is very pragmatic , If you have any questions about basic programming, please check the relevant articles .

like Python Friend, , Please pay attention to Python Basic column or Python From getting started to mastering the big column

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

copyright notice
author[Lei Xuewei],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/01/202201312001479161.html

Random recommended