当前位置:网站首页>[class, abstraction and inheritance]
[class, abstraction and inheritance]
2022-07-24 10:46:00 【lxw-pro】
python Rivers and lakes
- Class creation
- Simple class creation
- Class inheritance
- pandas Practice every day :
Personal Nickname :lxw-pro
Personal home page : Welcome to your attention My home page
Personal perception : “ Failure is the mother of success ”, This is the same truth , Sum up in failure , Grow in failure , To be IT A generation of masters in the world .
Class creation
init() Method — The function is to assign values to the attributes of objects
- The syntax for accessing attributes is : Object name . Property name
- The syntax of the access method is : Object name . Method name
in application , You can instantiate multiple objects in the same way
# Create a class Bird
class Bird:
def __init__(self, n, c, s):
self.name = n
self.color = c
self.size = s
self.age = 1
# Define methods get_description, Parameter is self, Auto in
def get_description(self):
description = f'{
self.name}{
self.color}{
self.size}'
print(description)
def get_age(self):
print(f"This bird is {
self.age}")
# Change the value of the attribute through methods :
def update_age(self, a):
self.age = a
# Instantiate objects my_bird, by my_bird Attribute ' Parrot ', ' green ', ' medium-sized '
my_bird = Bird(' Parrot ', ' green ', ' medium-sized ')
my_bird.get_description()
my_bird.get_age()
your_bird = Bird(' The sparrow ', ' gray ', ' medium-sized ')
print(f"Your bird's name is {
my_bird.name}")
your_bird.get_description()
# By accessing method statements my_bird.get_description(), Successful execution of method get_description() Print statements in
print(f"My bird's name is {
my_bird.name}")
print(f"My bird's color is {
my_bird.color}")
# Set default values for properties
# Modify attribute values directly , Statement for : Object name . Property name = value
my_bird.age = 3
my_bird.get_age()
my_bird.update_age(5)
my_bird.get_age()
Simple class creation
class Musician: # Create a class
glasses = " sunglasses " # Create class properties
def __init__(self, city): # Create initialization method
self.city = city # Assignment properties
print(' In organizational language ……')
def intr(self): # Create class methods
print(' I come from %s' % self.city)
gz = Musician(' Guizhou, China ') # Class instantiation object
print(gz.glasses)
gz.intr() # Calling class methods
ObjectIs the parent of all classes , Call it The root class isinstance() Function to determine Whether an instance belongs to a class
The relevant code is as follows :
class Car:
wheel = 4
def run(self):
print(' Yes %d A wheel , Can drive fast ' % self.wheel)
class BMW(Car):
pass # pass Express ' skip ', Do nothing else
BMW320 = BMW()
print(BMW320.wheel) # Running results :4
BMW320.run() # Running results : Yes 4 A wheel , Can drive fast
BENZ600 = Car() # Use Car Class to create Benz 600
BMW320 = BMW() # Use BMW Class creation BMW320
print(" verification : The instance created by the subclass also belongs to the parent class ")
print(isinstance(BENZ600, Car))
print(isinstance(BMW320, Car))
print(" verification : The instance created by the parent class does not belong to the subclass ")
print(isinstance(BENZ600, BMW))
print(" verification : All instances created by the class belong to the root class ")
print(isinstance(BENZ600, object))
print(isinstance(BMW320, object))
From the running results and combined with the code :
BENZ600 This instance belongs to both Car class , Also belong to Object class .
in other words ,BENZ600 Inherit Car class , Also inherited Object class , But don't inherit BMW class ;
Class inheritance
When creating a class , You don't have to start from scratch every time , Suppose that there are some common properties and methods between the new class we want to create and the class we have already created , We can inherit from an existing class , The new class is called Subclass , The inherited class is called Parent class .
inheritance , The subclass will get all the properties and methods of the parent class , And subclasses can also define their own properties and methods .
Grammar rules of subclasses :class New class name ( Parent class name )
Class inheritance , The subclass belongs to the parent class ; The instance created by the subclass also belongs to the parent class .
# Statement super() A function is a method used to call a parent class
class Penguin(Bird):
def __init__(self, n, c, s):
super().__init__(n, c, s)
self.swimming_distance = 100
def get_swimming_distance(self):
print(f" Penguins can swim {
self.swimming_distance} rice ")
my_bird = Penguin(' penguin ', ' Black and white ', ' Big ')
my_bird.get_description()
my_bird.get_swimming_distance()
Inheritance also includes multi-level inheritance and multi inheritance
Multiple inheritance
What is? Multiple inheritance ?
Subclasses can call the properties and methods of the parent class , You can also call the properties and methods of the parent class . This is it. Multiple inheritance .
# Stars
class Star:
glasses = " sunglasses "
# Musicians inherited stars
class Musician(Star):
loveMusic = True
# Rapper Inherited musicians
class Rapper(Musician):
pass
csunYuk = Rapper()
print(csunYuk.glasses)
print(csunYuk.loveMusic)
[^1] example csunYuk It's a class Rapper establish , It can call the parent class Musician Properties of , You can also call the parent class of the parent class Star Properties of .
multiple inheritance
What is? multiple inheritance Well ?
A class can inherit multiple classes , Grammar is class Z(X,Y)
# Musician
class Musician():
loveMusic = True
def intr(self):
print(" I like music ")
print(" I come from the music industry ")
# Speaker
class Orator():
speak = " Speak fluently "
def intr(self):
print(" I like speaking ")
print(" I come from the speech industry ")
# Rapper Inherited musicians and speakers
class Rapper(Musician, Orator):
pass
csunYuk = Rapper()
print(csunYuk.loveMusic)
print(csunYuk.speak)
csunYuk.intr()
csunYuk Inherited Parent class Musician Of attribute loveMusic, Also inherited Parent class Orator Of attribute speak;
When both parent classes have intr() Class method , It will inherit the parent class on the left first , That 's the parent class Musician Methods ;
In multiple inheritance , Subclasses inherit properties and methods from multiple parent classes , But it takes precedence over the properties and methods of the parent class on the left
Class customization
Subclasses can be customized on the basis of inheriting the parent class : You can create new attributes 、 The new method ; You can also change the inherited properties or methods .
On the basis of inheriting the parent class , It can be changed
# Musician
class Musician():
loveMusic = True
def intr(self):
print(" I like music ")
print(" I come from the music industry ")
def sing(self):
print(" I'm singing ")
# Rapper Inheritor
class Rapper(Musician): # Class inheritance
def sing(self): # Class customization , Change method
print(" I sing in the form of speaking ")
csunYuk = Rapper()
csunYuk.sing()
# csunYuk It's through Rapper Instantiated object , Rapper Class inheritance Musician class ,
# Nature will inherit Musician Class method sing;
# however Rapper Class will sing Method to rewrite , cause csunYuk.sing() At the end of the run ,
# The result of printing is “ I sing in the form of speaking ”
————————————————————————————————————————————
pandas Practice every day :
EXCEL Documents are prepared in advance :

Guide library 、 Reading documents
# -*- coding = utf-8 -*-
# @Time : 2022/7/23 20:38
# @Author : lxw_pro
# @File : pandas-6 practice .py
# @Software : PyCharm
import pandas as pd
df = pd.read_excel('text5.xlsx')
26、 Look at the index 、 Data types and memory information
df.info()
The program runs as follows :
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 8 entries, 0 to 7
Data columns (total 7 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 Unnamed: 0 8 non-null int64
1 Unnamed: 0.1 8 non-null object
2 project 8 non-null object
3 popularity 8 non-null int64
4 test_time 8 non-null datetime64[ns]
5 date 8 non-null datetime64[ns]
6 time 8 non-null object
dtypes: datetime64[ns](2), int64(2), object(3)
memory usage: 576.0+ bytes
27、 View summary statistics for numeric Columns
print('describe', df.loc[:, ['popularity']].describe())
The program runs as follows :
describe popularity
count 8.000000
mean 125.000000
std 28.963031
min 84.000000
25% 94.250000
50% 143.000000
75% 146.500000
max 149.000000
28、 Add a new column based on popularity Divide the data into n Group
fz = [0, 80, 120, 150]
fz_names = [' good I', ' good II', ' good ']
df['scores'] = pd.cut(df['popularity'], fz, labels=fz_names)
print(df)
The program runs as follows :
Unnamed: 0 Unnamed: 0.1 project ... date time scores
0 0 00:00:00 Python ... 2022-06-20 18:30:20 good II
1 1 1 Java ... 2022-06-18 19:40:20 good II
2 2 2 C ... 2022-06-08 13:33:20 good
3 3 3 MySQL ... 2021-12-23 11:26:20 good
4 4 4 Linux ... 2021-12-20 18:20:20 good II
5 5 5 Math ... 2022-07-20 16:30:20 good
6 6 6 English ... 2022-06-23 15:30:20 good
7 7 7 Python ... 2022-07-19 09:30:20 good
[8 rows x 8 columns]
29、 according to popularity Columns sort data in descending order
print(df.sort_values('popularity', ascending=False))
The program runs as follows :
Unnamed: 0 Unnamed: 0.1 project ... date time scores
7 7 7 Python ... 2022-07-19 09:30:20 good
5 5 5 Math ... 2022-07-20 16:30:20 good
6 6 6 English ... 2022-06-23 15:30:20 good
2 2 2 C ... 2022-06-08 13:33:20 good
3 3 3 MySQL ... 2021-12-23 11:26:20 good
0 0 00:00:00 Python ... 2022-06-20 18:30:20 good II
1 1 1 Java ... 2022-06-18 19:40:20 good II
4 4 4 Linux ... 2021-12-20 18:20:20 good II
[8 rows x 8 columns]
30、 Take out No 6 Row data
print(df.loc[5])
The program runs as follows :
Unnamed: 0 5
Unnamed: 0.1 5
project Math
popularity 148
test_time 2022-07-20 16:30:20
date 2022-07-20 00:00:00
time 16:30:20
scores good
Name: 5, dtype: object
A word a day :
In life , The important thing is not victory , But struggle , Something indispensable to life , Not to win , But once fought without regret .
Ongoing update …
give the thumbs-up , Your recognition is my creation
power!
Collection , Your favor is my effortDirection!
Comment on , Your opinion is my progressWealth!
Focus on , Your love is my lastinginsist!
Welcome to your attention WeChat official account 【 Programmed life 6】, Discuss and study together !!!
边栏推荐
- PC博物馆(2) 1972年 HP-9830A
- Design of dual machine hot standby scheme
- Cross platform audio playback Library
- Detailed explanation of Flink operation architecture
- Five best WordPress advertising plug-ins
- Machine learning quiz (11) verification code recognition test - deep learning experiment using QT and tensorflow2
- ECCV 2022 | 清华提出首个嵌入光谱稀疏性的Transformer
- 每日三题 7.22
- This usage, SystemVerilog syntax
- Sentinel three flow control modes
猜你喜欢

Princeton chendanqi: how to make the "big model" smaller
![[electronic device note 3] capacitance parameters and type selection](/img/d2/1ddb309a8f3cfe5f65c71964052006.png)
[electronic device note 3] capacitance parameters and type selection

MySQL - 索引的隐藏和删除

很佩服的一个Google大佬,离职了。。

Sentinel 流量控制快速入门

Real time weather API

MySQL - unique index

零基础学习CANoe Panel(6)—— 开关/显示控件(Switch/Indicator)

机器学习小试(10)使用Qt与Tensorflow创建CNN/FNN测试环境

Intranet remote control tool under Windows
随机推荐
Five best WordPress advertising plug-ins
MySQL - full text index
常量指针、指针常量
[electronic device note 3] capacitance parameters and type selection
IEPE vibration sensor synchronous signal acquisition card /icp synchronous data network acquisition module
简单使用 MySQL 索引
Review of new services and functions of Amazon cloud technology in June 2022
Erlang learning 01
Activity review | Anyuan AI X machine heart series lecture No. 1 | deepmind research scientist rohin Shah shares "finding a safe path for AgI"
Flink 运行架构详解
Google cooperates with colleges and universities to develop a general model, proteogan, which can design and generate proteins with new functions
N-tree, page_ Size, database strict mode modification, and the difference between delete and drop in the database
MySQL - multi column index
Image processing: floating point number to fixed point number
[dish of learning notes dog learning C] initial level of pointer
二叉树基础知识概览
DSP CCS software simulation
binlog、iptables防止nmap扫描、xtrabackup全量+增量备份以及redlog和binlog两者的关系
《nlp入门+实战:第二章:pytorch的入门使用 》
563页(30万字)智慧化工园区(一期)总体设计方案
