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 :
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 :
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
The sidebar is recommended
- Python crawls the map of Gaode and the weather conditions of each city
- leetcode 1275. Find Winner on a Tic Tac Toe Game(python)
- leetcode 2016. Maximum Difference Between Increasing Elements(python)
- Run through Python date and time processing (Part 2)
- Application of urllib package in Python
- Django API Version (II)
- Python utility module playsound
- Database addition, deletion, modification and query of Python Sqlalchemy basic operation
- Tiobe November programming language ranking: Python surpasses C language to become the first! PHP is about to fall out of the top ten?
- Learn how to use opencv and python to realize face recognition!
guess what you like
-
Using OpenCV and python to identify credit card numbers
-
Principle of Python Apriori algorithm (11)
-
Python AI steals your voice in 5 seconds
-
A glance at Python's file processing (Part 1)
-
Python cloud cat
-
Python crawler actual combat, pyecharts module, python data analysis tells you which goods are popular on free fish~
-
Using pandas to implement SQL group_ concat
-
How IOS developers learn Python Programming 8 - set type 3
-
windows10+apache2. 4 + Django deployment
-
Django parser
Random recommended
- leetcode 1560. Most Visited Sector in a Circular Track(python)
- leetcode 1995. Count Special Quadruplets(python)
- How to program based on interfaces using Python
- leetcode 1286. Iterator for Combination(python)
- leetcode 1418. Display Table of Food Orders in a Restaurant (python)
- Python Matplotlib drawing histogram
- Python development foundation summary (VII) database + FTP + character coding + source code security
- Python modular package management and import mechanism
- Django serialization (II)
- Python dataloader error "dataloader worker (PID XXX) is killed by signal" solution
- apache2. 4 + Django + windows 10 Automated Deployment
- leetcode 1222. Queens That Can Attack the King(python)
- leetcode 1387. Sort Integers by The Power Value (python)
- Tiger sniffing 24-hour praise device, a case with a crawler skill, python crawler lesson 7-9
- Python object oriented programming 01: introduction classes and objects
- Baidu Post: high definition Python
- Python Matplotlib drawing contour map
- Python crawler actual combat, requests module, python realizes IMDB movie top data visualization
- Python classic: explain programming and development from simple to deep and step by step
- Python implements URL availability monitoring and instant push
- Python avatar animation, come and generate your own animation avatar
- leetcode 1884. Egg Drop With 2 Eggs and N Floors(python)
- leetcode 1910. Remove All Occurrences of a Substring(python)
- Python and binary
- First acquaintance with Python class
- [Python data collection] scrapy book acquisition and coding analysis
- Python crawler from introduction to mastery (IV) extracting information from web pages
- Python crawler from entry to mastery (III) implementation of simple crawler
- The apscheduler module in Python implements scheduled tasks
- 1379. Find the same node in the cloned binary tree (Java / C + + / Python)
- Python connects redis, singleton and thread pool, and resolves problems encountered
- Python from 0 to 1 (day 11) - Python data application 1
- Python bisect module
- Python + OpenGL realizes real-time interactive writing on blocks with B-spline curves
- Use the properties of Python VTK implicit functions to select and cut data
- Learn these 10000 passages and become a humorous person in the IT workplace. Python crawler lessons 8-9
- leetcode 986. Interval List Intersections(python)
- leetcode 1860. Incremental Memory Leak(python)
- How to teach yourself Python? How long will it take?
- Python Matplotlib drawing pie chart