60000 word summary of Python basic knowledge points, liver explosion, staying up late in a week [recommended collection]

Five packs of spicy strips! 2021-09-15 12:41:15
word summary python basic knowledge


Hello everyone , I'm spicy .

I'm going to bring it to you today Python Summary of basic knowledge points , It's no exaggeration to say that I finished it in a week , This is the first shot , If you like to remember the third company , I'll update the next shot quickly , Try to finish this series , I hope to get your support .

Catalog

notes

Variable

Output

Input

Convert data type

Operator

Conditional statements

  loop

character string

list

Tuples

Dictionaries

aggregate

Public operation

The derived type

Function one

Function two

Function three

File operations

Object oriented fundamentals

object-oriented - Inherit

object-oriented - other  

abnormal

Modules and packages

package


notes

  • Classification of notes

    • A single : # The comment , Shortcut key ctrl+/

    • Multiple lines :""" The comment """ or ''' The comment '''

  • The interpreter does not execute annotation content

Annotations fall into two categories :== Single-line comments == and == Multiline comment ==.

  • Single-line comments

Only one line can be annotated , The grammar is as follows :

# The comment 
  • Multiline comment

You can annotate multiple lines of content , It is usually used to comment a piece of code , The grammar is as follows :

"""
The first line notes
Second line of notes
The third line notes
"""
​
'''
notes 1
notes 2
notes 3
'''

Shortcut key : ==ctrl + /==

Variable

A variable is just the name of the memory address where the current data is stored .

identifier

The identifier naming rule is Python A unified specification for defining various names in , As follows :

  • By digital 、 Letter 、 Underline composition

  • Cannot start with a number

  • You can't use built-in keywords

  • Case sensitive

  Naming habits

  • Know what you know .

  • Hump : That is, every word is capitalized , for example :MyName.

  • Little hump : the second ( contain ) Later words are capitalized , for example :myName.

  • Underline : for example :my_name.

Understanding data types

How to detect data types :type()

a = 1
print(type(a))  # <class 'int'> -- integer
​
b = 1.1
print(type(b))  # <class 'float'> -- floating-point
​
c = True
print(type(c))  # <class 'bool'> -- Boolean type
​
d = '12345'
print(type(d))  # <class 'str'> -- character string
​
e = [10, 20, 30]
print(type(e))  # <class 'list'> -- list
​
f = (10, 20, 30)
print(type(f))  # <class 'tuple'> -- Tuples
​
h = {10, 20, 30}
print(type(h))  # <class 'set'> -- aggregate
​
g = {'name': 'TOM', 'age': 20}
print(type(g))  # <class 'dict'> -- Dictionaries 

  Output

effect : Program output content to users

print('hello Python')
​
age = 19
print(age)
​
# demand : Output “ My age this year is 19 year ”

Format symbol

Format symbol transformation
==%s== character string
==%d== Signed decimal integers
==%f== Floating point numbers
%c character
%u An unsigned decimal integer
%o Octal integer
%x Hexadecimal integer ( A lowercase letter ox)
%X Hexadecimal integer ( Capitalization OX)
%e Scientific enumeration ( A lowercase letter 'e')
%E Scientific enumeration ( Capitalization 'E')
%g %f and %e Abbreviation
%G %f and %E Abbreviation

Escape character

  • \n: Line break .

  • \t: tabs , One tab key (4 A space ) Distance of .

Terminator

print(' Output content ', end="\n")

stay Python in ,print(), Default by oneself end="\n" This newline Terminator , So it leads to every two print Direct line feed display , Users can change the terminator as required .

  Input

stay Python in , The function of the program to receive the data input by the user is input .

input(" Prompt information ")

The characteristics of input

  • When the program is executed to input, Waiting for user input , Do not continue down until the input is complete .

  • stay Python in ,input After receiving user input , Generally stored in variables , Easy to use .

  • stay Python in ,input The received data input by any user will be treated as a string .

Convert data type

function explain
==int(x [,base ])== take x Convert to an integer
==float(x )== take x Convert to a floating point number
complex(real [,imag ]) Create a complex number ,real It is the real part ,imag It is the imaginary part
==str(x )== Put the object x Convert to string
repr(x ) Put the object x Converts to an expression string
==eval(str )== Used to calculate the validity in a string Python expression , And returns an object
==tuple(s )== The sequence of s Converts to a tuple
==list(s )== The sequence of s Convert to a list
chr(x ) Convert an integer to a Unicode character
ord(x ) Converts a character to its ASCII An integer value
hex(x ) Convert an integer to a hexadecimal string
oct(x ) Converts an integer to an octal string
bin(x )

Convert an integer to a binary string

  Common functions for converting data types

  • int()

  • float()

  • str()

  • list()

  • tuple()

  • eval()

Operator

Arithmetic operator

Operator describe example
+ Add 1 + 1 The output is 2
- reduce 1-1 The output is 0
* ride 2 * 2 The output is 4
/ except 10 / 2 The output is 5
// to be divisible by 9 // 4 The output is 2
% Remainder 9 % 4 The output is 1
** Index 2 ** 4 The output is 16, namely 2 * 2 * 2 * 2
() parentheses Parentheses are used to increase the priority of operations , namely (1 + 2) * 3 The output is 9

Assignment operator

Operator describe example
= assignment take = The result on the right is assigned to the variable on the left of the equal sign

Compound assignment operator

Operator describe example
+= Addition assignment operator c += a Equivalent to c = c + a
-= Subtraction assignment operator c -= a Equivalent to c = c- a
*= Multiplication assignment operator c *= a Equivalent to c = c * a
/= Division assignment operator c /= a Equivalent to c = c / a
//= The integer division assignment operator c //= a Equivalent to c = c // a
%= The remainder assignment operator c %= a Equivalent to c = c % a
**= Power assignment operator c ** = a Equivalent to c = c ** a

Comparison operator

Operator describe example
== Judge equal . If the results of two operands are equal , Then the conditional result is true (True), Otherwise, the conditional result is false (False) Such as a=3,b=3, be (a == b) by True
!= It's not equal to . If the results of two operands are not equal , Then the condition is true (True), Otherwise, the conditional result is false (False) Such as a=3,b=3, be (a == b) by True Such as a=1,b=3, be (a != b) by True
> Whether the left-hand result of the operator is greater than the right-hand result of the operator , If it is greater than , Then the condition is true , Otherwise it is false Such as a=7,b=3, be (a > b) by True
< Whether the result of the operands on the left side of the operator is less than the result of the operands on the right side , If it is less than , Then the condition is true , Otherwise it is false Such as a=7,b=3, be (a < b) by False
>= Whether the left-hand result of the operator is greater than or equal to the right-hand result of the operator , If it is greater than , Then the condition is true , Otherwise it is false Such as a=7,b=3, be (a < b) by False Such as a=3,b=3, be (a >= b) by True
<= Whether the left-hand result of the operator is less than or equal to the right-hand result of the operator , If it is less than , Then the condition is true , Otherwise it is false Such as a=3,b=3, be (a <= b) by True

Logical operators

Operator Logical expression describe example
and x and y Boolean " And ": If x by False,x and y return False, Otherwise it returns y Value . True and False, return False.
or x or y Boolean " or ": If x yes True, It returns True, Otherwise it returns y Value . False or True, return True.
not not x Boolean " Not ": If x by True, return False . If x by False, It returns True. not True return False, not False return True

Conditional statements

Suppose a scenario :

In fact, the so-called judgment here is conditional statement , namely If the condition holds, execute some code , If the condition does not hold, the code will not be executed .

grammar

if Conditions :
    Conditional execution code 1
    Conditional execution code 2
  ......

if...else...

effect : Implementation of conditions if Code below ; If the conditions are not established, the execution will be carried out else Code below .

if Conditions :
    Conditional execution code 1
    Conditional execution code 2
  ......
else:
    Code executed when the condition does not hold 1
    Code executed when the condition does not hold 2
  ......

example : Length of service

age = int(input(' Please enter your age :'))
if age < 18:
   print(f' Your age is {age}, One ')
elif (age >= 18) and (age <= 60):
   print(f' Your age is {age}, Legal length of service ')
elif age > 60:
   print(f' Your age is {age}, You can retire ')

expand :age >= 18 and age <= 60 It can be reduced to 18 <= age <= 60.

if nesting

if Conditions 1:
Conditions 1 Set up the code to execute
    Conditions 1 Set up the code to execute
   
   if Conditions 2:
  Conditions 2 Set up the code to execute
        Conditions 2 Set up the code to execute
 

application : Guessing game

Demand analysis :

  • The characters involved in the game

    • The player

      • Hand punch

    • The computer

      • Random punch

  • Judgement of winning or losing

    • Players win

    The player The computer
    stone scissors
    scissors cloth
    cloth stone
    • It ends in a draw

      • Players punch and The computer punches the same way

    • The computer wins

Random approach :

  1. export random modular

  2. random.randint( Start , end )

"""
Tips :0- stone ,1- scissors ,2- cloth
1. Punch
Players input and punch
The computer punches at random
​
2. Judgement of winning or losing
Players win
It ends in a draw
The computer wins
"""
​
# Import random modular
import random
​
# Calculate the random number of the fist produced by the computer
computer = random.randint(0, 2)
print(computer)
​
player = int(input(' Please punch :0- stone ,1- scissors ,2- cloth :'))
​
# Players win p0:c1 or p1:c2 or p2:c0
if (player == 0 and computer == 1) or (player == 1 and computer == 2) or (player == 2 and computer == 0):
   print(' Players win ')
​
# It ends in a draw : The player == The computer
elif player == computer:
   print(' It ends in a draw ')
else:
   print(' The computer wins ')

Ternary operator

Ternary operators are also called ternary operators .

The grammar is as follows :

 value 1 if Conditions else value 2

Quick experience :

a = 1
b = 2
​
c = a if a > b else b
print(c)

  loop

The role of circulation : Make code execute repeatedly more efficiently .

Classification of cycles

stay Python in , The cycle is divided into while and for Two kinds of , The final effect is the same .

while The grammar of

while Conditions :
    Conditional repeated code 1
    Conditional repeated code 2
  ......

while Application

Calculation 1-100 Cumulative sum

analysis :1-100 Summation of , namely 1 + 2 + 3 + 4 +…., That is, the result of adding the first two numbers + Next number ( The previous number + 1).

i = 1
result = 0
while i <= 100:
   result += i
   i += 1
​
# Output 5050
print(result)

Be careful : To verify the accuracy of the program , You can reduce it first , After the verification results are correct , Then to 1-100 Add up .

Calculation 1-100 Even sum

analysis :1-100 Even sum of , namely 2 + 4 + 6 + 8...., The way to get even numbers is as follows :

  • Even numbers are sum 2 The remainder is 0 The number of , You can add conditional statements to determine whether it is even , Even numbers add up

  • The initial value is 0 / 2 , The counter accumulates every time 2

Method 1 : Conditional judgment and 2 The remainder is accumulated

# Method 1 : Conditional judgment and 2 Take the remainder as 0 Then the cumulative calculation
i = 1
result = 0
while i <= 100:
   if i % 2 == 0:
       result += i
   i += 1
​
# Output 2550
print(result)

Method 2 : Counter control

# Method 2 : The counter control increment is 2
i = 0
result = 0
while i <= 100:
   result += i
   i += 2
​
# Output 2550
print(result)

while A nested loop

A synopsis of the story : One day, my girlfriend got angry again , punishment : say 3 All over “ wife , I was wrong ”, Is this program a loop ? But if your girlfriend says : And I'm going to brush the bowl for dinner today , How to write this program ?

while Conditions :
   print(' wife , I was wrong ')
print(' Brush the dinner bowl ')

But if the girlfriend is still angry , Keep the punishment going 3 Every day , There's how to write the program ?

while Conditions :
while Conditions :
print(' wife , I was wrong ')
print(' Brush the dinner bowl ')

while Conditions 1:
Conditions 1 Set up the code to execute
......
while Conditions 2:
Conditions 2 Set up the code to execute
......

summary : So-called while A nested loop , It's just one. while There's one nested inside while Writing , Every while The basic grammar is the same as before .

for loop

grammar

for Temporary variable in Sequence :
Repeated code 1
Repeated code 2
......

else

Circulation can be combined with else In combination with ,else The indented code below refers to == The code to be executed when the loop ends normally ==.

while...else

demand : My girlfriend is angry , To punish : Continuum theory 5 All over “ wife , I was wrong ”, If the apology is normal, my girlfriend will forgive me , How to write this program ?

i = 1
while i <= 5:
print(' wife , I was wrong ')
i += 1
print(' My daughter-in-law has forgiven me ...')

reflection : This print Can it be executed without a loop ?

grammar

while Conditions :
Conditional repeated code
else:
The code to be executed after the normal end of the loop 

Example

i = 1
while i <= 5:
print(' wife , I was wrong ')
i += 1
else:
print(' My daughter-in-law has forgiven me , I'm so happy , Ha ha ha ha ')

for...else

grammar

for Temporary variable in Sequence :
Repeated code
...
else:
The code to be executed after the normal end of the loop 

So-called else It refers to the code to be executed after the normal end of the loop , That is, if it is break Termination of the cycle ,else The code indented below will not execute .

Example

str1 = 'itheima'
for i in str1:
print(i)
else:
print(' The code executed after the normal end of the loop ')

summary

  • The role of circulation : Repeated execution of control code

  • while grammar

while Conditions :
Conditional repeated code 1
Conditional repeated code 2
......
  • while Loop nesting Syntax

while Conditions 1:
Conditions 1 Set up the code to execute
......
while Conditions 2:
Conditions 2 Set up the code to execute
......
  • for Cyclic grammar

for Temporary variable in Sequence :
Repeated code 1
Repeated code 2
......
  • break Exit the whole cycle

  • continue Exit this cycle , Continue with the next iteration of the code

  • else

    • while and for All can cooperate with else Use

    • else Meaning of code indented below : Code executed when the loop ends normally

    • break Terminating a loop does not execute else Code indented below

    • continue Execute by exiting the loop else Code indented below

character string

The string is Python The most commonly used data type in . We usually use quotation marks to create strings . Creating a string is simple , Just assign a value to the variable .

a = 'hello world'
b = "abcdefg"
print(type(a))
print(type(b))

Be careful : The console displays the result as <class 'str'>, That is, the data type is str( character string ).

String output

print('hello world')
​
name = 'Tom'
print(' My name is %s' % name)
print(f' My name is {name}')

String input

stay Python in , Use input() Receive user input .

  • Code

name = input(' Please enter your name :')
print(f' The name you entered is {name}')
print(type(name))
​
password = input(' Please enter your password :')
print(f' The password you entered is {password}')
print(type(password))

section

Slicing refers to the operation of intercepting part of the operation object . character string 、 list 、 Tuples Both support slicing .

grammar

 Sequence [ Starting position subscript : End position subscript : step ]

Be careful

  1. It does not contain the data corresponding to the ending position subscript , Both positive and negative integers are OK ;

  2. Step size is the selection interval , Both positive and negative integers are OK , The default step size is 1.

Experience

name = "abcdefg"
​
print(name[2:5:1])  # cde
print(name[2:5])  # cde
print(name[:5])  # abcde
print(name[1:])  # bcdefg
print(name[:])  # abcdefg
print(name[::2])  # aceg
print(name[:-1])  # abcdef, negative 1 Represents the penultimate data
print(name[-4:-1])  # def
print(name[::-1])  # gfedcba

modify

Modifying strings , It refers to modifying the data in a string in the form of a function .

  • replace(): Replace

  1. grammar

 String sequence .replace( Old substring , New substring , Number of replacements )

Be careful : Replacement times if you find out the number of substrings , Then the number of substitutions is the number of occurrences of the substring .

  1. Quick experience

mystr = "hello world and itcast and itheima and Python"
​
# result :hello world he itcast he itheima he Python
print(mystr.replace('and', 'he'))
# result :hello world he itcast he itheima he Python
print(mystr.replace('and', 'he', 10))
# result :hello world and itcast and itheima and Python
print(mystr)

Be careful : Data can be divided into two categories according to whether they can be modified directly == Variable type == and == Immutable type == Two kinds of . When data of string type is modified, the original string cannot be changed , A type that cannot be modified directly is an immutable type .

  • split(): Splits the string according to the specified character .

  1. grammar

 String sequence .split( Split characters , num)

Be careful :num Represents the number of times the split character appears , The number of data to be returned is num+1 individual .

  1. Quick experience

mystr = "hello world and itcast and itheima and Python"
​
# result :['hello world ', ' itcast ', ' itheima ', ' Python']
print(mystr.split('and'))
# result :['hello world ', ' itcast ', ' itheima and Python']
print(mystr.split('and', 2))
# result :['hello', 'world', 'and', 'itcast', 'and', 'itheima', 'and', 'Python']
print(mystr.split(' '))
# result :['hello', 'world', 'and itcast and itheima and Python']
print(mystr.split(' ', 2))

Be careful : If the split character is a substring of the original string , After splitting, the substring is lost .

  • join(): Merge strings with a single character or substring , That is, combine multiple strings into a new string .

  1. grammar

 Character or substring .join( A sequence of multiple strings )
  1. Quick experience

list1 = ['chuan', 'zhi', 'bo', 'ke']
t1 = ('aa', 'b', 'cc', 'ddd')
# result :chuan_zhi_bo_ke
print('_'.join(list1))
# result :aa...b...cc...ddd
print('...'.join(t1))

  • capitalize(): Converts the first character of a string to uppercase .

mystr = "hello world and itcast and itheima and Python"
​
# result :Hello world and itcast and itheima and python
print(mystr.capitalize())

Be careful :capitalize() After function conversion , Only the first character of a string is capitalized , All the other characters are lowercase .

  • title(): Convert the first letter of each word in a string to uppercase .

mystr = "hello world and itcast and itheima and Python"
​
# result :Hello World And Itcast And Itheima And Python
print(mystr.title())

  • lower(): Convert uppercase to lowercase in a string .

mystr = "hello world and itcast and itheima and Python"
​
# result :hello world and itcast and itheima and python
print(mystr.lower())

  • upper(): Convert small write to uppercase in a string .

mystr = "hello world and itcast and itheima and Python"
​
# result :HELLO WORLD AND ITCAST AND ITHEIMA AND PYTHON
print(mystr.upper())

Judge

The so-called judgment is to judge whether it is true or false , The result is a Boolean data type :True or False.

  • startswith(): Check whether the string starts with the specified substring , Yes, go back to True, Otherwise return to False. If you set the start and end position subscripts , Check... Within the specified range .

  1. grammar

 String sequence .startswith( Substring , Starting position subscript , End position subscript )
  1. Quick experience

mystr = "hello world and itcast and itheima and Python   "
​
# result :True
print(mystr.startswith('hello'))
​
# result False
print(mystr.startswith('hello', 5, 20))

  • endswith():: Check whether the string ends with the specified substring , Yes, go back to True, Otherwise return to False. If you set the start and end position subscripts , Check... Within the specified range .

  1. grammar

 String sequence .endswith( Substring , Starting position subscript , End position subscript )
  1. Quick experience

mystr = "hello world and itcast and itheima and Python"
​
# result :True
print(mystr.endswith('Python'))
​
# result :False
print(mystr.endswith('python'))
​
# result :False
print(mystr.endswith('Python', 2, 20))

  • isalpha(): Returns if the string has at least one character and all characters are letters True, Otherwise return to False.

mystr1 = 'hello'
mystr2 = 'hello12345'
​
# result :True
print(mystr1.isalpha())
​
# result :False
print(mystr2.isalpha())

  • isdigit(): Returns if the string contains only numbers True Otherwise return to False.

mystr1 = 'aaa12345'
mystr2 = '12345'
​
# result : False
print(mystr1.isdigit())
​
# result :False
print(mystr2.isdigit())

  • isalnum(): Returns if the string has at least one character and all characters are letters or numbers return True, Otherwise return to False.

mystr1 = 'aaa12345'
mystr2 = '12345-'
​
# result :True
print(mystr1.isalnum())
​
# result :False
print(mystr2.isalnum())

  • isspace(): If the string contains only white space , Then return to True, Otherwise return to False.

mystr1 = '1 2 3 4 5'
mystr2 = '     '
​
# result :False
print(mystr1.isspace())
​
# result :True
print(mystr2.isspace())

summary

  • Subscript

    • The number of bytes allocated by the computer to each element in the data sequence 0 Starting number

  • section

 The sequence of [ Starting position subscript : End position subscript : step ]
  • Common operation methods

    • find()

    • index()

list

reflection : There's a person's name (TOM) How to write a stored program ?

answer : Variable .

reflection : If a class 100 Students , Everyone's name has to be stored , How to write a program ? Statement 100 Is it a variable ?

answer : Just list , Lists can store multiple data at once .

The format of the list

[ data 1, data 2, data 3, data 4......]

Lists can store multiple data at once , And can be different data types .

Common operations of list

The function of lists is to store multiple data at one time , The operations that programmers can perform on these data are : increase 、 Delete 、 Change 、 check .

lookup

Subscript

name_list = ['Tom', 'Lily', 'Rose']
​
print(name_list[0])  # Tom
print(name_list[1])  # Lily
print(name_list[2])  # Rose

function

  • index(): Returns the subscript of the location of the specified data .

  1. grammar

 List sequence .index( data , Starting position subscript , End position subscript )
  1. Quick experience

name_list = ['Tom', 'Lily', 'Rose']
​
print(name_list.index('Lily', 0, 2))  # 1

Be careful : If the searched data does not exist, an error will be reported .

  • count(): Count the number of times the specified data appears in the current list .

name_list = ['Tom', 'Lily', 'Rose']
​
print(name_list.count('Lily'))  # 1
  • len(): Access list length , That is, the number of data in the list .

name_list = ['Tom', 'Lily', 'Rose']
​
print(len(name_list))  # 3

Judge whether it exists

  • in: Determine whether the specified data is in a list sequence , If you are returning True, Otherwise return to False

name_list = ['Tom', 'Lily', 'Rose']
​
# result :True
print('Lily' in name_list)
​
# result :False
print('Lilys' in name_list)

  • not in: Judge that the specified data is not in a list sequence , If not returning True, Otherwise return to False

name_list = ['Tom', 'Lily', 'Rose']
​
# result :False
print('Lily' not in name_list)
​
# result :True
print('Lilys' not in name_list)
  • Experience cases

demand : Find out if the name entered by the user already exists .

name_list = ['Tom', 'Lily', 'Rose']
​
name = input(' Please enter the name you want to search :')
​
if name in name_list:
   print(f' The name you entered is {name}, The name already exists ')
else:
   print(f' The name you entered is {name}, The name doesn't exist ')

increase

effect : Add the specified data to the list .

  • append(): Append data to the end of the list .

  1. grammar

 List sequence .append( data )
  1. Experience

name_list = ['Tom', 'Lily', 'Rose']
​
name_list.append('xiaoming')
​
# result :['Tom', 'Lily', 'Rose', 'xiaoming']
print(name_list)

When appending data to the list , Add the specified data directly to the original list , That is, the original list has been modified , So the list is variable type data .

  1. Be careful

If append() The appended data is a sequence , The entire sequence is appended to the list

name_list = ['Tom', 'Lily', 'Rose']
​
name_list.append(['xiaoming', 'xiaohong'])
​
# result :['Tom', 'Lily', 'Rose', ['xiaoming', 'xiaohong']]
print(name_list)

  • extend(): Append data to the end of the list , If the data is a sequence , Then add the data of this sequence to the list one by one .

  1. grammar

 List sequence .extend( data )
  1. Quick experience

    2.1 Single data

name_list = ['Tom', 'Lily', 'Rose']
​
name_list.extend('xiaoming')
​
# result :['Tom', 'Lily', 'Rose', 'x', 'i', 'a', 'o', 'm', 'i', 'n', 'g']
print(name_list)

2.2 Sequence data

name_list = ['Tom', 'Lily', 'Rose']
​
name_list.extend(['xiaoming', 'xiaohong'])
​
# result :['Tom', 'Lily', 'Rose', 'xiaoming', 'xiaohong']
print(name_list)

  • insert(): Add data at the specified location .

  1. grammar

 List sequence .insert( Location subscript , data )
  1. Quick experience

name_list = ['Tom', 'Lily', 'Rose']
​
name_list.insert(1, 'xiaoming')
​
# result :['Tom', 'xiaoming', 'Lily', 'Rose']
print(name_list)

Delete

  • del

  • grammar

del The goal is 

Quick experience

Delete list

name_list = ['Tom', 'Lily', 'Rose']
​
# result : Wrong presentation :name 'name_list' is not defined
del name_list
print(name_list)

Delete specified data

name_list = ['Tom', 'Lily', 'Rose']
​
del name_list[0]
​
# result :['Lily', 'Rose']
print(name_list)

  • pop(): Delete the data of the specified subscript ( The default is the last ), And return the data .

  • grammar

 List sequence .pop( Subscript )
  1. Quick experience

name_list = ['Tom', 'Lily', 'Rose']
​
del_name = name_list.pop(1)
​
# result :Lily
print(del_name)
​
# result :['Tom', 'Rose']
print(name_list)

  • remove(): Remove the first match of a data in the list .

  1. grammar

 List sequence .remove( data )
  1. Quick experience

name_list = ['Tom', 'Lily', 'Rose']
​
name_list.remove('Rose')
​
# result :['Tom', 'Lily']
print(name_list)

  • clear(): clear list

name_list = ['Tom', 'Lily', 'Rose']
​
name_list.clear()
print(name_list) # result : []

modify

  • Modify the specified subscript data

name_list = ['Tom', 'Lily', 'Rose']
​
name_list[0] = 'aaa'
​
# result :['aaa', 'Lily', 'Rose']
print(name_list)

  • Inversion :reverse()

num_list = [1, 5, 2, 3, 6, 8]
​
num_list.reverse()
​
# result :[8, 6, 3, 2, 5, 1]
print(num_list)

  • Sort :sort()

  1. grammar

 List sequence .sort( key=None, reverse=False)

Be careful :reverse Represents a collation ,reverse = True Descending , reverse = False Ascending ( Default )

  1. Quick experience

num_list = [1, 5, 2, 3, 6, 8]
​
num_list.sort()
​
# result :[1, 2, 3, 5, 6, 8]
print(num_list)

Copy

function :copy()

name_list = ['Tom', 'Lily', 'Rose']
​
name_li2 = name_list.copy()
​
# result :['Tom', 'Lily', 'Rose']
print(name_li2)

List nesting

The so-called list nesting means that a list contains other sub lists .

Application scenarios : To store class one 、 Two 、 Names of students in three classes , And the names of students in each class are in a list .

name_list = [[' Xiao Ming ', ' Xiaohong ', ' Little green '], ['Tom', 'Lily', 'Rose'], [' Zhang San ', ' Li Si ', ' Wang Wu ']]

reflection : How to find data " Li Si "?

# First step : Press the subscript to find the list where Li Si is located
print(name_list[2])
​
# The second step : From Li Si's list , Then click the subscript to find the data Li Si
print(name_list[2][1])

summary

  • The format of the list

[ data 1, data 2, data 3]
  • Common operation methods

    • index()

    • len()

    • append()

    • pop()

    • remove()

  • List nesting

name_list = [[' Xiao Ming ', ' Xiaohong ', ' Little green '], ['Tom', 'Lily', 'Rose'], [' Zhang San ', ' Li Si ', ' Wang Wu ']]
name_list[2][1]

Tuples

reflection : If you want to store multiple data , But these data can't be modified , How do you do it? ?

answer : list ? Lists can store multiple data at once , But the data in the list is allowed to change .

num_list = [10, 20, 30]
num_list[0] = 100

== A tuple can store multiple data , Data in tuples cannot be modified .==

Define tuples

Tuple characteristics : Define tuple usage == parentheses ==, And == comma == Separate data , Data can be of different data types .

# Multiple data tuples
t1 = (10, 20, 30)
​
# A single data tuple
t2 = (10,)

Be careful : If the tuple defined has only one data , Then add a comma after the data , Otherwise, the data type is the only data type of this data

t2 = (10,)
print(type(t2))  # tuple
​
t3 = (20)
print(type(t3))  # int
​
t4 = ('hello')
print(type(t4))  # str

Common operation of tuples

Tuple data does not support modification , Only search is supported , As follows :

  • Find data by subscript

tuple1 = ('aa', 'bb', 'cc', 'bb')
print(tuple1[0])  # aa

  • index(): Find a data , If the data exists, return the corresponding subscript , Otherwise, the report will be wrong , Syntax and lists 、 A string of index In the same way .

tuple1 = ('aa', 'bb', 'cc', 'bb')
print(tuple1.index('aa'))  # 0

  • count(): Count the number of times a data appears in the current tuple .

tuple1 = ('aa', 'bb', 'cc', 'bb')
print(tuple1.count('bb'))  # 2

  • len(): Count the number of data in tuples .

tuple1 = ('aa', 'bb', 'cc', 'bb')
print(len(tuple1))  # 4

Be careful : If the direct data in the tuple is modified, an error will be reported immediately

tuple1 = ('aa', 'bb', 'cc', 'bb')
tuple1[0] = 'aaa'

But if there's a list in the tuple , Modifying the data in the list is supported , So consciousness is very important .

tuple2 = (10, 20, ['aa', 'bb', 'cc'], 50, 30)
print(tuple2[2])  # Access to the list
​
# result :(10, 20, ['aaaaa', 'bb', 'cc'], 50, 30)
tuple2[2][0] = 'aaaaa'
print(tuple2)

summary

  • Define tuples

t1 = (10, 20, 30)
​
t2 = (10,)
  • Common operation methods

    • index()

    • len()

Dictionaries

reflection 1: If there is more than one data , for example :'Tom', ' male ', 20, How to quickly store ?

answer : list

list1 = ['Tom', ' male ', 20]

reflection 2: How to find data 'Tom'?

answer : Found subscript 0 That's all .

list1[0]

reflection 3: If the data order changes in the future , As shown below , Can also be used list1[0] Access to data 'Tom' Do you ?.

list1 = [' male ', 20, 'Tom']

answer : You can't , data 'Tom' Now the subscript is 2.

reflection 4: The order of the data changes , The subscript of each data will also change , How to ensure that the same standard can be used to find data before and after the data order changes ?

answer : Dictionaries , The data in the dictionary is == Key value pair == Form appears , Dictionary data has nothing to do with data order , The dictionary does not support subscripts , Later, no matter how the data changes , Just look up the data according to the name of the corresponding key .

The syntax for creating a dictionary

Dictionary features :

  • The symbol is == Curly braces ==

  • The data is == Key value pair == Form appears

  • Between key value pairs == comma == separate

# There is a data dictionary
dict1 = {'name': 'Tom', 'age': 20, 'gender': ' male '}
​
# An empty dictionary
dict2 = {}
​
dict3 = dict()

Be careful : The key before the colon is called the key (key), abbreviation k; The value after the colon is (value), abbreviation v.

Dictionary common operation

increase

How to write it :== Dictionary sequence [key] = value ==

Be careful : If key If it exists, modify this key Corresponding value ; If key If it does not exist, add this key value pair .

dict1 = {'name': 'Tom', 'age': 20, 'gender': ' male '}
​
dict1['name'] = 'Rose'
# result :{'name': 'Rose', 'age': 20, 'gender': ' male '}
print(dict1)
​
dict1['id'] = 110
​
# {'name': 'Rose', 'age': 20, 'gender': ' male ', 'id': 110}
print(dict1)

Be careful : Dictionaries are variable types .

Delete

  • del() / del: Delete the dictionary or the specified key value pair in the dictionary .

dict1 = {'name': 'Tom', 'age': 20, 'gender': ' male '}
​
del dict1['gender']
# result :{'name': 'Tom', 'age': 20}
print(dict1)

  • clear(): Empty dictionary

dict1 = {'name': 'Tom', 'age': 20, 'gender': ' male '}
​
dict1.clear()
print(dict1)  # {}

Change

How to write it :== Dictionary sequence [key] = value ==

Be careful : If key If it exists, modify this key Corresponding value  ; If key If it does not exist, add this key value pair .

check

Value search

dict1 = {'name': 'Tom', 'age': 20, 'gender': ' male '}
print(dict1['name'])  # Tom
print(dict1['id'])  # Report errors 

If the current search key There is , Then return the corresponding value ; Otherwise, an error will be reported .

get()

  • grammar

 Dictionary sequence .get(key, The default value is )

Be careful : If the current search key If not, the second parameter is returned ( The default value is ), If you omit the second parameter , Then return to None.

  • Quick experience

dict1 = {'name': 'Tom', 'age': 20, 'gender': ' male '}
print(dict1.get('name'))  # Tom
print(dict1.get('id', 110))  # 110
print(dict1.get('id'))  # None

keys()

dict1 = {'name': 'Tom', 'age': 20, 'gender': ' male '}
print(dict1.keys())  # dict_keys(['name', 'age', 'gender'])

values()

dict1 = {'name': 'Tom', 'age': 20, 'gender': ' male '}
print(dict1.values())  # dict_values(['Tom', 20, ' male '])

items()

dict1 = {'name': 'Tom', 'age': 20, 'gender': ' male '}
print(dict1.items())  # dict_items([('name', 'Tom'), ('age', 20), ('gender', ' male ')])

summary

  • Definition dictionary

dict1 = {'name': 'Python', 'age': 30}
​
dict2 = {}
​
dict3 = dict()
  • Common operations

    • increase / Change

 Dictionary sequence [key] = value 
  • lookup

    • Dictionary sequence [key]

    • keys()

    • values()

    • items()

aggregate

Create set

Create a collection using {} or set(), But if you want to create an empty collection, you can only use set(), because {} Used to create an empty dictionary .

s1 = {10, 20, 30, 40, 50}
print(s1)
​
s2 = {10, 30, 20, 10, 30, 40, 30, 50}
print(s2)
​
s3 = set('abcdefg')
print(s3)
​
s4 = set()
print(type(s4))  # set
​
s5 = {}
print(type(s5))  # dict

characteristic :

  1. Sets can remove duplicate data ;

  2. The set data is out of order , Therefore, subscripts are not supported

Collection common operation methods

Add data

  • add()

s1 = {10, 20}
s1.add(100)
s1.add(10)
print(s1)  # {100, 10, 20}

Because the set has the function of de duplication , therefore , When the data added to the set is the existing data of the current set , Nothing is done .

  • update(), The additional data is a sequence .

s1 = {10, 20}
# s1.update(100) # Report errors
s1.update([100, 200])
s1.update('abc')
print(s1)

  Delete data

  • remove(), Delete the specified data in the collection , If the data does not exist, an error will be reported .

s1 = {10, 20}
​
s1.remove(10)
print(s1)
​
s1.remove(10)  # Report errors
print(s1)

  • discard(), Delete the specified data in the collection , If the data does not exist, no error will be reported .

s1 = {10, 20}
​
s1.discard(10)
print(s1)
​
s1.discard(10)
print(s1)

  • pop(), Randomly delete a data in the set , And return this data .

s1 = {10, 20, 30, 40, 50}
​
del_num = s1.pop()
print(del_num)
print(s1)

  Find data

  • in: Judge whether the data is in the set sequence

  • not in: Judge that the data is not in the set sequence

s1 = {10, 20, 30, 40, 50}
​
print(10 in s1)
print(10 not in s1)

summary

  • Create set

    • There are data sets

    s1 = { data 1, data 2, ...}
    • No data set

    s1 = set()
  • Common operations

    • Add data

      • add()

      • update()

    • Delete data

      • remove()

      • discard()

Public operation

Operator

Operator describe Supported container types
+ Merge character string 、 list 、 Tuples
* Copy character string 、 list 、 Tuples
in Whether elements exist character string 、 list 、 Tuples 、 Dictionaries
not in Does the element not exist character string 、 list 、 Tuples 、 Dictionaries

+

# 1. character string
str1 = 'aa'
str2 = 'bb'
str3 = str1 + str2
print(str3)  # aabb
​
​
# 2. list
list1 = [1, 2]
list2 = [10, 20]
list3 = list1 + list2
print(list3)  # [1, 2, 10, 20]
​
# 3. Tuples
t1 = (1, 2)
t2 = (10, 20)
t3 = t1 + t2
print(t3)  # (10, 20, 100, 200)

*

# 1. character string
print('-' * 10)  # ----------
​
# 2. list
list1 = ['hello']
print(list1 * 4)  # ['hello', 'hello', 'hello', 'hello']
​
# 3. Tuples
t1 = ('world',)
print(t1 * 4)  # ('world', 'world', 'world', 'world')

in or not in

# 1. character string
print('a' in 'abcd')  # True
print('a' not in 'abcd')  # False
​
# 2. list
list1 = ['a', 'b', 'c', 'd']
print('a' in list1)  # True
print('a' not in list1)  # False
​
# 3. Tuples
t1 = ('a', 'b', 'c', 'd')
print('aa' in t1)  # False
print('aa' not in t1)  # True

Public methods

function describe
len() Count the number of elements in the container
del or del() Delete
max() Returns the maximum value of the element in the container
min() Returns the minimum value of the element in the container
range(start, end, step) Generated from start To end The number of , In steps of step, for for Recycling
enumerate() Function is used to traverse a data object ( As listing 、 Tuples or strings ) Combined into an index sequence , List both data and data index , Generally used in for Cycle of .

len()

# 1. character string
str1 = 'abcdefg'
print(len(str1))  # 7
​
# 2. list
list1 = [10, 20, 30, 40]
print(len(list1))  # 4
​
# 3. Tuples
t1 = (10, 20, 30, 40, 50)
print(len(t1))  # 5
​
# 4. aggregate
s1 = {10, 20, 30}
print(len(s1))  # 3
​
# 5. Dictionaries
dict1 = {'name': 'Rose', 'age': 18}
print(len(dict1))  # 2

del()

# 1. character string
str1 = 'abcdefg'
del str1
print(str1)
​
# 2. list
list1 = [10, 20, 30, 40]
del(list1[0])
print(list1)  # [20, 30, 40]

max()

# 1. character string
str1 = 'abcdefg'
print(max(str1))  # g
​
# 2. list
list1 = [10, 20, 30, 40]
print(max(list1))  # 40

min()

# 1. character string
str1 = 'abcdefg'
print(min(str1))  # a
​
# 2. list
list1 = [10, 20, 30, 40]
print(min(list1))  # 10

range()

# 1 2 3 4 5 6 7 8 9
for i in range(1, 10, 1):
   print(i)
​
# 1 3 5 7 9
for i in range(1, 10, 2):
   print(i)
​
# 0 1 2 3 4 5 6 7 8 9
for i in range(10):
   print(i)

Be careful :range() The generated sequence does not contain end Numbers .

enumerate()

  • grammar

enumerate( Traversable objects , start=0)

Be careful :start Parameter is used to set the starting value of the subscript of traversal data , The default is 0.

  • Quick experience

list1 = ['a', 'b', 'c', 'd', 'e']
​
for i in enumerate(list1):
   print(i)
​
for index, char in enumerate(list1, start=1):
   print(f' The subscript is {index}, The corresponding character is {char}')

Container type conversion

tuple()

effect : Convert a sequence to a tuple

list1 = [10, 20, 30, 40, 50, 20]
s1 = {100, 200, 300, 400, 500}
​
print(tuple(list1))
print(tuple(s1))

list()

effect : Convert a sequence into a list

t1 = ('a', 'b', 'c', 'd', 'e')
s1 = {100, 200, 300, 400, 500}
​
print(list(t1))
print(list(s1))

set()

effect : Converting a sequence into a set

list1 = [10, 20, 30, 40, 50, 20]
t1 = ('a', 'b', 'c', 'd', 'e')
​
print(set(list1))
print(set(t1))

Be careful :

  1. Collection can quickly complete list de duplication

  2. Collection does not support subscripts

summary

  • Operator

    • +

    • in / not in

  • Public methods

    • len()

    • del()

    • range()

    • enumerate()

  • Data type conversion

    • tuple()

    • list()

    • set()

The derived type

effect : Create a regular list with an expression or control a regular list .

List derivation is also called list generation .

Quick experience

demand : Create a 0-10 A list of .

  • while Cycle to achieve

# 1. Prepare an empty list
list1 = []
​
# 2. Writing cycle , Append the numbers to the empty list in turn list1 in
i = 0
while i < 10:
   list1.append(i)
   i += 1
​
print(list1)
  • for Cycle to achieve

list1 = []
for i in range(10):
   list1.append(i)
​
print(list1)
  • List derivation implementation

list1 = [i for i in range(10)]
print(list1)

belt if List derivation of

demand : establish 0-10 Even list of

  • Method 1 :range() Step size implementation

list1 = [i for i in range(0, 10, 2)]
print(list1)
  • Method 2 :if Realization

list1 = [i for i in range(10) if i % 2 == 0]
print(list1)

Multiple for Loop to implement the list derivation

demand : The creation list is as follows :

[(1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
  • The code is as follows :

list1 = [(i, j) for i in range(1, 3) for j in range(3)]
print(list1)

Dictionary derivation

reflection : If you have the following two lists :

list1 = ['name', 'age', 'gender']
list2 = ['Tom', 20, 'man']

How to quickly merge into a dictionary ?

answer : Dictionary derivation

The function of dictionary derivation : Quickly merge lists into dictionaries or extract target data from dictionaries .

Quick experience

  1. Create a dictionary : Dictionaries key yes 1-5 Numbers ,value It's this number 2 Power .

dict1 = {i: i**2 for i in range(1, 5)}
print(dict1)  # {1: 1, 2: 4, 3: 9, 4: 16}

  1. Merge two lists into one dictionary

list1 = ['name', 'age', 'gender']
list2 = ['Tom', 20, 'man']
​
dict1 = {list1[i]: list2[i] for i in range(len(list1))}
print(dict1)
  1. Extract the target data from the dictionary

counts = {'MBP': 268, 'HP': 125, 'DELL': 201, 'Lenovo': 199, 'acer': 99}
​
# demand : The number of computers mentioned above is greater than or equal to 200 Dictionary data for
count1 = {key: value for key, value in counts.items() if value >= 200}
print(count1)  # {'MBP': 268, 'DELL': 201}

Set derivation

demand : Create a collection , The data are listed below 2 Power .

list1 = [1, 1, 2]

The code is as follows :

list1 = [1, 1, 2]
set1 = {i ** 2 for i in list1}
print(set1)  # {1, 4}

Be careful : Set has data De duplication function .

summary

  • The function of derivation : Simplify the code

  • Deductive writing

# List derivation
[xx for xx in range()]
​
# Dictionary derivation
{xx1: xx2 for ... in ...}
​
# Set derivation
{xx for xx in ...}

Function one

Function function

demand : The user to ATM Cash withdrawal by machine :

  1. Display after entering the password " Select function " Interface

  2. Display after querying balance " Select function " Interface

  3. take 2000 Show after money " Select function " Interface

characteristic : Show “ Select function ” The interface needs to be repeatedly output to the user , How to achieve ?

The function will be == A code block with independent functions == Integrate into a whole and name it , Where needed == Call this name == The corresponding requirements can be completed .

Function in the development process , It can be realized more efficiently == code reuse ==.

To use a function

Defined function

def Function name ( Parameters ):
    Code 1
    Code 2
  ......

Call function

 Function name ( Parameters )

Be careful :

  1. Different needs , Parameters are optional .

  2. stay Python in , The function must == Define before use ==.

Quick experience

demand : Reappear ATM Money withdrawal function .

  1. Build the overall framework ( Reproduction demand )

print(' The password is correct and the login is successful ')
​
# Show " Select function " Interface
​
print(' Balance query completed ')
​
# Show " Select function " Interface
​
print(' Take it 2000 Yuan ')
​
# Show " Select function " Interface 
  1. determine “ Select function ” Content of the interface

print(' Check the balance ')
print(' deposit ')
print(' Withdraw money ')
  1. encapsulation " Select function "

Be careful : You must define the function first , Then call the function .

# encapsulation ATM Machine function options -- Defined function
def select_func():
   print('----- Please select the function -----')
   print(' Check the balance ')
   print(' deposit ')
   print(' Withdraw money ')
   print('----- Please select the function -----')
  1. Call function

When you need to show “ Select function ” Call the function at the location of the function .

print(' The password is correct and the login is successful ')
# Show " Select function " Interface -- Call function
select_func()
​
print(' Balance query completed ')
# Show " Select function " Interface -- Call function
select_func()
​
print(' Take it 2000 Yuan ')
# Show " Select function " Interface -- Call function
select_func()

Parameter action of function

reflection : The completion requirements are as follows : One function completes two numbers 1 and 2 Addition operation of , How to write a program ?

# Defined function
def add_num1():
   result = 1 + 2
   print(result)
​
​
# Call function
add_num1()

reflection : Above add_num1 Functions can only complete numbers 1 and 2 Addition operation of , If you want this function to be more flexible , You can calculate the sum of any two numbers specified by the user , How to write a program ?

analysis : The user should specify the specific number when calling the function , When defining a function, you need to receive the number specified by the user . The number specified when calling the function and the number received when defining the function are the parameters of the function .

# When the function is defined, the parameters to receive user data are also defined a and b,a and b It's a parameter
def add_num2(a, b):
   result = a + b
   print(result)
​
​
# The real data is passed in when the function is called 10 and 20, The real data is the real parameter
add_num2(10, 20)

Function return value

for example : We go shopping in the supermarket , Like buying cigarettes , After giving the money , Will the salesperson return us the cigarette , In the function , If you need to return the result to the user, you need to use the function return value .

def buy():
   return ' smoke '
​
# Use variables to save the return value of a function
goods = buy()
print(goods)

application

demand : Make a calculator , Calculate the sum of any two numbers , And save the results .

def sum_num(a, b):
   return a + b
​
​
# use result Variable holds the return value of the function
result = sum_num(1, 2)
print(result)

Function documentation

reflection : After defining a function , How the programmer writes the program can prompt the function quickly ?

answer : notes

reflection : If there's a lot of code , Do we need to find the location of the function definition in a lot of code to see the comments ? If you want to view the function more conveniently ?

answer : Function documentation

The documentation of functions is also called documentation of functions .

grammar

  • The documentation for defining functions

def Function name ( Parameters ):
   """ Describes the location of the document """
    Code
  ......
  • Check the documentation for the function

help( Function name )

Quick experience

def sum_num(a, b):
   """ Sum function """
   return a + b
​
​
help(sum_num)

Function nested call

Nested function calls refer to == One function calls another function ==.

  • Example

def testB():
   print('---- testB start----')
   print(' Here is testB Function execution code ...( Omit )...')
   print('---- testB end----')
​
def testA():
   print('---- testA start----')
   testB()
   print('---- testA end----')
​
testA()

  • If the function A in , Another function called B, So let's start with the function B Only after all the tasks in are executed will we return to the last function A Location of execution .

Function application

Function calculation

  1. Find the sum of three numbers

def sum_num(a, b, c):
   return a + b + c
​
​
result = sum_num(1, 2, 3)
print(result)  # 6

  1. Find the average of three numbers

def average_num(a, b, c):
   sumResult = sum_num(a, b, c)
   return sumResult / 3
​
result = average_num(1, 2, 3)
print(result)  # 2.0

summary

  • Function function : Encapsulates the code , Efficient code reuse

  • Function steps

    • Defined function

    def Function name ():
        Code 1
        Code 2
      ...
    • Call function

     Function name ()
  • The parameters of the function : Function call can pass in real data , Increase the flexibility of using functions

    • Shape parameter : Parameters written in function definition ( Untrue data )

    • Actual parameters : Parameters written when a function is called ( Real data )

  • The return value of the function

    • effect : After function call , Return the required calculation results

    • How to write it

    return expression 
  • Function documentation

    • effect : Save information about function explanations

    • How to write it

    def Function name ():
       """ Function documentation """
  • Function nested call : Nested calls to another function inside a function

Function two

Variable scope

Variable scope refers to the range in which a variable takes effect , There are two main categories :== local variable == and == Global variables ==.

  • local variable

The so-called local variable is the variable defined inside the function body , That is, it only takes effect inside the function body .

def testA():
   a = 100
​
   print(a)
​
​
testA()  # 100
print(a)  # Report errors :name 'a' is not defined

Variable a Is defined in testA Variables within a function , If the function is accessed outside, an error will be reported immediately .

The role of local variables : Inside the body of the function , Save data temporarily , That is, when the function call is completed , Destroy the local variable .

  • Global variables

The so-called global variable , Refers to the body of a function 、 Variables that can take effect outside .

reflection : If there's a data , In function A And the function B We should use , What should I do ?

answer : Store this data in a global variable .

# Define global variables a
a = 100
​
​
def testA():
   print(a)  # Accessing global variables a, And print variables a Stored data
​
​
def testB():
   print(a)  # Accessing global variables a, And print variables a Stored data
​
​
testA()  # 100
testB()  # 100

reflection :testB Function demand modification variable a The value of is 200, How to modify a program ?

a = 100
​
​
def testA():
   print(a)
​
​
def testB():
   a = 200
   print(a)
​
​
testA()  # 100
testB()  # 200
print(f' Global variables a = {a}')  # Global variables a = 100

reflection : stay testB intra-function a = 200 The variables in the a You are modifying global variables a Do you ?

answer : No . Observe the above code and find ,15 Line get a The data of 100, Global variables are still defined a Time is worth , Instead of returning

testB intra-function 200. Sum up :testB intra-function a = 200 Defines a local variable .

reflection : How to modify a global variable inside a function body ?

a = 100
​
​
def testA():
   print(a)
​
​
def testB():
   # global Keyword declaration a Global variable
   global a
   a = 200
   print(a)
​
​
testA()  # 100
testB()  # 200
print(f' Global variables a = {a}')  # Global variables a = 200

Multi function program execution flow

Generally, in the actual development process , A program often consists of multiple functions ( Classes will be explained in the following knowledge ) form , And multiple functions share some data , As shown below :

  • Shared global variables

# 1. Define global variables
glo_num = 0
​
​
def test1():
   global glo_num
   # Modify global variables
   glo_num = 100
​
​
def test2():
   # call test1 Modified global variable in function
   print(glo_num)
   
​
# 2. call test1 function , Execute function internal code : Declare and modify global variables
test1()
# 3. call test2 function , Execute function internal code : Print
test2()  # 100
  • The return value is passed as a parameter

def test1():
   return 50
​
​
def test2(num):
   print(num)
​
​
# 1. Save function test1 The return value of
result = test1()
​
​
# 2. Pass the variable where the function return value is located as a parameter to test2 function
test2(result)  # 50

The return value of the function

reflection : If a function is like two return ( As shown below ), How to execute the program ?

def return_num():
   return 1
   return 2
​
​
result = return_num()
print(result)  # 1

answer : Only the first return, The reason is because return You can exit the current function , Lead to return The code below does not execute .

reflection : If a function has multiple return values , How to write code ?

def return_num():
   return 1, 2
​
​
result = return_num()
print(result)  # (1, 2)

Be careful :

  1. return a, b How to write it , When returning multiple data , The default is tuple type .

  2. return You can connect the list later 、 Tuple or dictionary , To return multiple values .

The parameters of the function

Positional arguments

Positional arguments : When a function is called, parameters are passed according to the parameter position defined by the function .

def user_info(name, age, gender):
   print(f' What's your name {name}, Age is {age}, Gender is {gender}')
​
​
user_info('TOM', 20, ' male ')

Be careful : The order and number of parameters passed and defined must be consistent .

Key parameters

Function call , adopt “ key = value ” Form to be specified . It makes the function clearer 、 Easy to use , At the same time, the order requirement of parameters is cleared .

def user_info(name, age, gender):
   print(f' What's your name {name}, Age is {age}, Gender is {gender}')
​
​
user_info('Rose', age=20, gender=' Woman ')
user_info(' Xiao Ming ', gender=' male ', age=16)

Be careful : When a function is called , If there are position parameters , The positional parameter must precede the keyword parameter , But there is no order between keyword parameters .

Default parameters

Default parameters are also called default parameters , Used to define functions , Provide default values for parameters , When calling a function, the value of the default parameter may not be passed ( Be careful : All positional parameters must appear before the default parameters , Including function definition and call ).

def user_info(name, age, gender=' male '):
   print(f' What's your name {name}, Age is {age}, Gender is {gender}')
​
​
user_info('TOM', 20)
user_info('Rose', 18, ' Woman ')

Be careful : When a function is called , If it is the default parameter value, modify the default parameter value ; Otherwise use this default value .

Indefinite length parameter

Variable length parameter is also called variable parameter . Used to determine how many parameters will be passed when calling ( It's OK not to pass on the ginseng ) Scene . here , Available packages (packing) Positional arguments , Or package keyword parameters , To pass parameters , It will be very convenient .

  • Package location delivery

def user_info(*args):
   print(args)
​
​
# ('TOM',)
user_info('TOM')
# ('TOM', 18)
user_info('TOM', 18)

Be careful : All the parameters passed in will be args Variable collection , It will be combined into a tuple based on the position of the incoming parameters (tuple),args It's a tuple type , This is the package location transfer .

  • Package keyword delivery

def user_info(**kwargs):
   print(kwargs)
​
​
# {'name': 'TOM', 'age': 18, 'id': 110}
user_info(name='TOM', age=18, id=110)

Sum up : Whether it's package location delivery or package keyword delivery , It's all a packaging process .

Unpacking and exchanging variable values

unpacking

  • unpacking : Tuples

def return_num():
   return 100, 200
​
​
num1, num2 = return_num()
print(num1)  # 100
print(num2)  # 200
  • unpacking : Dictionaries

dict1 = {'name': 'TOM', 'age': 18}
a, b = dict1
​
# Unpack the dictionary , What comes out is the dictionary key
print(a)  # name
print(b)  # age
​
print(dict1[a])  # TOM
print(dict1[b])  # 18

Exchange variable values

demand : There are variables a = 10 and b = 20, Exchange the values of two variables .

  • Method 1

Storing data with the help of a third variable .

# 1. Define intermediate variables
c = 0
​
# 2. take a Data stored in c
c = a
​
# 3. take b The data of 20 Assign values to the a, here a = 20
a = b
​
# 4. Before c The data of 10 Assign values to the b, here b = 10
b = c
​
print(a)  # 20
print(b)  # 10
  • Method 2

a, b = 1, 2
a, b = b, a
print(a)  # 2
print(b)  # 1

quote

Understanding references

stay python in , Value is transmitted by reference .

We can use id() To determine whether two variables are references to the same value . We can id Value is understood as the address identification of that memory .

# 1. int type
a = 1
b = a
​
print(b)  # 1
​
print(id(a))  # 140708464157520
print(id(b))  # 140708464157520
​
a = 2
print(b)  # 1, explain int The type is immutable
​
print(id(a))  # 140708464157552, At this point, you get the data 2 Memory address of
print(id(b))  # 140708464157520
​
​
# 2. list
aa = [10, 20]
bb = aa
​
print(id(aa))  # 2325297783432
print(id(bb))  # 2325297783432
​
​
aa.append(30)
print(bb)  # [10, 20, 30], The list is of variable type
​
print(id(aa))  # 2325297783432
print(id(bb))  # 2325297783432

Reference as argument

The code is as follows :

def test1(a):
   print(a)
   print(id(a))
​
   a += a
​
   print(a)
   print(id(a))
​
​
# int: Before and after calculation id Values are different
b = 100
test1(b)
​
# list : Before and after calculation id Same value
c = [11, 22]
test1(c)

Variable and immutable types

The so-called variable type and immutable type refer to : Data can be modified directly , If you can modify it directly, it is variable , Otherwise, it is immutable .

  • Variable type

    • list

    • Dictionaries

    • aggregate

  • Immutable type

    • integer

    • floating-point

    • character string

    • Tuples

summary

  • Variable scope

    • overall situation : Functions can take effect both inside and outside

    • Local : The current function body takes effect internally

  • Function multiple return value writing method

return expression 1, expression 2...
  • The parameters of the function

    • Positional arguments

      • The number and writing order of formal parameters and arguments must be consistent

    • Key parameters

      • How to write it : key=value

      • characteristic : Formal parameters and arguments can be written in different order ; Keyword parameters must be written after positional parameters

    • Default parameters

      • The default parameter is the default parameter

      • How to write it :key=vlaue

    • Variable length position parameters

      • Collect all location parameters , Returns a tuple

    • Variable length keyword parameter

      • Collect all keyword parameters , Return a dictionary

  • quote :Python in , Data is passed by reference

Function three

application : Student management system

System introduction

demand : Enter the system display system function interface , Function as follows :

  • 1、 Add students

  • 2、 Delete student

  • 3、 Modify student information

  • 4、 Query student information

  • 5、 Display all student information

  • 6、 Exit the system

System total 6 Features , Users select according to their own needs .

Step analysis

  1. Display function interface

  2. The user enters the function serial number

  3. According to the function serial number entered by the user , Perform different functions ( function )

    3.1 Defined function

    3.2 Call function

Demand fulfillment

Display function interface

Defined function print_info, Responsible for displaying system functions .

def print_info():
   print('-' * 20)
   print(' Welcome to the student management system ')
   print('1: Add students ')
   print('2: Delete student ')
   print('3: Modify student information ')
   print('4: Query student information ')
   print('5: Display all student information ')
   print('6: Exit the system ')
   print('-' * 20)
   
   
print_info()

The user enters the serial number , Select function

user_num = input(' Please select the function serial number you need :')

According to the user's choice , Perform different functions

if user_num == '1':
   print(' Add students ')
elif user_num == '2':
   print(' Delete student ')
elif user_num == '3':
   print(' Modify student information ')
elif user_num == '4':
   print(' Query student information ')
elif user_num == '5':
   print(' Display all student information ')
elif user_num == '6':
   print(' Exit the system ')

In the work , You need to tune your code according to your actual needs .

  1. The code that the user selects the system function needs to be recycled , Until the user actively exits the system .

  2. If user input 1-6 Other numbers , You need to prompt the user .

while True:
   # 1. Display function interface
   print_info()
   
   # 2. User selection function
   user_num = input(' Please select the function serial number you need :')
​
   # 3. According to the user's choice , Perform different functions
   if user_num == '1':
       print(' Add students ')
   elif user_num == '2':
       print(' Delete student ')
   elif user_num == '3':
       print(' Modify student information ')
   elif user_num == '4':
       print(' Query student information ')
   elif user_num == '5':
       print(' Display all student information ')
   elif user_num == '6':
       print(' Exit the system ')
   else:
       print(' Input error , Please re-enter !!!')

Define functions for different functions

All function functions operate student information , All stored student information should be a == Global variables ==, The data type is == list ==.

info = []

1.3.4.1 Add students

  • Demand analysis

  1. Receive user input student information , And save

  2. Judge whether to add student information

    2.1 If the student name already exists , Then, an error is reported

    2.2 If the student name does not exist , Prepare an empty dictionary , Append the data entered by the user to the dictionary , Then add dictionary data to the list

  3. Corresponding if The function is called where the condition holds

  • Code implementation

def add_info():
   """ Add students """
   # Receive user input student information
   new_id = input(' Please enter the student number :')
   new_name = input(' Please enter a name :')
   new_tel = input(' Please enter your mobile number :')
   
​
   # Statement info Global variable
   global info
​
   # Detect whether the name entered by the user exists , If there is an error, an error message will be reported
   for i in info:
       if new_name == i['name']:
           print(' The user already exists !')
           return
​
   # If the name entered by the user does not exist , Then add the student information
   info_dict = {}
   
   # Append the data entered by the user to the dictionary
   info_dict['id'] = new_id
   info_dict['name'] = new_name
   info_dict['tel'] = new_tel
   
   # Append the learner's dictionary data to the list
   info.append(info_dict)
   
   print(info)

Delete student

  • Demand analysis

Delete according to the student name entered by the user

  1. User input target student name

  2. Check if this student exists

    2.1 If there is , Delete this data from the list

    2.2 If it doesn't exist , Prompt “ The user does not exist ”

  3. Corresponding if The function is called where the condition holds

  • Code implementation

# Delete student
def del_info():
   """ Delete student """
   # 1. The user enters the name of the student to delete
   del_name = input(' Please enter the name of the student to delete :')
​
   global info
   # 2. Judge whether the student exists : If the entered name exists, it will be deleted , Otherwise, an error message will be given
   for i in info:
       if del_name == i['name']:
           info.remove(i)
           break
   else:
       print(' The student does not exist ')
​
   print(info)

Modify student information

  • Demand analysis

  1. User input target student name

  2. Check if this student exists

    2.1 If there is , Modify the student's information , E.g. mobile number

    2.2 If it doesn't exist , False report

  3. Corresponding if The function is called where the condition holds

  • Code implementation

# Modify the function
def modify_info():
   """ Modify the function """
   # 1. The user enters the name of the student to be modified
   modify_name = input(' Please enter the name of the student to be modified :')
​
   global info
   # 2. Judge whether the student exists : If the entered name exists, modify the mobile phone number , Otherwise, an error message will be given
   for i in info:
       if modify_name == i ['name']:
           i['tel'] = input(' Please enter a new mobile number :')
           break
   else:
       print(' The student does not exist ')
   
   print(info)

Query student information

  • Demand analysis

  1. User input target student name

  2. Check if the delegates are present

    2.1 If there is , The information of this student will be displayed

    2.2 If it doesn't exist , Then, an error is reported

  3. Corresponding if The function is called where the condition holds

  • Code implementation

# Query students
def search_info():
   """ Query students """
   # 1. Enter the name of the student you want to find :
   search_name = input(' Please enter the name of the student you want to find :')
​
   global info
   # 2. Judge whether the student exists : If the entered name exists, the student information will be displayed , Otherwise, an error message will be given
   for i in info:
       if search_name == i['name']:
           print(' The student information found is as follows :----------')
           print(f" The student number of the student is {i['id']}, Name is {i['name']}, The cell phone number is {i['tel']}")
           break
   else:
       print(' The student does not exist ')

Display all student information

  • Demand analysis

Print all student information

  • Code implementation

# Display all student information
def print_all():
   """ Display all student information """
   print(' Student number \t full name \t cell-phone number ')
   for i in info:
       print(f'{i["id"]}\t{i["name"]}\t{i["tel"]}')

1.3.4.6 Exit the system

Enter the function serial number in the user interface 6 Exit the system when , The code is as follows :

   ......
   elif user_num == '6':
       exit_flag = input(' Are you sure you want to quit ?yes or no')
       if exit_flag == 'yes':
           break

  recursive

Recursion is a programming idea , Application scenarios :

  1. In our daily development , If you want to traverse all the files under a folder , Recursive implementation is usually used ;

  2. In the following algorithm courses , Many algorithms are inseparable from recursion , for example : Quick sort .

The characteristics of recursion

  • The function itself calls itself

  • There must be an exit

application :3 Add up the sum of the numbers within

  • Code

# 3 + 2 + 1
def sum_numbers(num):
   # 1. If it is 1, Go straight back to 1 -- exit
   if num == 1:
       return 1
   # 2. If not 1, Repeat the accumulation and return the result
   return num + sum_numbers(num-1)
​
​
sum_result = sum_numbers(3)
# The output is 6
print(sum_result)

lambda expression

If a function has a return value , And there's only one code , have access to lambda simplify .

lambda grammar

lambda parameter list : expression 

Be careful

  • lambda The parameters of the expression are optional , The parameters of the function are in the lambda It is completely applicable in the expression .

  • lambda An expression can take any number of arguments, but it can only return the value of one expression .

Quick start

# function
def fn1():
   return 200
​
​
print(fn1)
print(fn1())
​
​
# lambda expression
fn2 = lambda: 100
print(fn2)
print(fn2())

Be careful : Print directly lambda expression , This is the output lambda Memory address of

Example : Calculation a + b

Function implementation

def add(a, b):
   return a + b
​
​
result = add(1, 2)
print(result)

reflection : The need is simple , Are there many codes ?

lambda Realization

fn1 = lambda a, b: a + b
print(fn1(1, 2))

lambda The parametric form of

No parameter

fn1 = lambda: 100
print(fn1())

One parameter

fn1 = lambda a: a
print(fn1('hello world'))

Default parameters

fn1 = lambda a, b, c=100: a + b + c
print(fn1(10, 20))

Variable parameters :*args

fn1 = lambda *args: args
print(fn1(10, 20, 30))

Be careful : The variable parameters here are passed into lambda after , The return value is a tuple .

Variable parameters :**kwargs

fn1 = lambda **kwargs: kwargs
print(fn1(name='python', age=20))

lambda Application

With judgment lambda

fn1 = lambda a, b: a if a > b else b
print(fn1(1000, 500))

List data by Dictionary key Value ordering for

students = [
  {'name': 'TOM', 'age': 20},
  {'name': 'ROSE', 'age': 19},
  {'name': 'Jack', 'age': 22}
]
​
# Press name Values in ascending order
students.sort(key=lambda x: x['name'])
print(students)
​
# Press name Values in descending order
students.sort(key=lambda x: x['name'], reverse=True)
print(students)
​
# Press age Values in ascending order
students.sort(key=lambda x: x['age'])
print(students)

Higher order function

== Pass in the function as an argument ==, Such functions are called higher-order functions , Higher order function is the embodiment of functional programming . Functional programming is a highly abstract programming paradigm .

Experience higher order functions

stay Python in ,abs() Function can complete the calculation of the absolute value of a number .

abs(-10)  # 10

round() Function can complete the rounding calculation of numbers .

round(1.2)  # 1
round(1.9)  # 2

demand : Any two numbers , Arrange the numbers according to the specified requirements before summing .

  • Method 1

def add_num(a, b):
   return abs(a) + abs(b)
​
​
result = add_num(-1, 2)
print(result)  # 3
  • Method 2

def sum_num(a, b, f):
   return f(a) + f(b)
​
​
result = sum_num(-1, 2, abs)
print(result)  # 3

Be careful : After comparing the two methods , Find out , Method 2 The code will be more concise , More flexible functions .

Functional programming uses a lot of functions , Reduced code duplication , So the program is shorter , Faster development .

Built in higher order function

 map()

map(func, lst), The function variable passed in func Effect to lst In each element of the variable , And make a new list of the results (Python2)/ iterator (Python3) return .

demand : Calculation list1 Of each number in the sequence 2 Power .

list1 = [1, 2, 3, 4, 5]
​
​
def func(x):
   return x ** 2
​
​
result = map(func, list1)
​
print(result)  # <map object at 0x0000013769653198>
print(list(result))  # [1, 4, 9, 16, 25]

reduce()

reduce(func,lst), among func There must be two parameters . Every time func The result of the calculation continues to be cumulative with the next element of the sequence .

Be careful :reduce() Incoming parameter func Must receive 2 Parameters .

demand : Calculation list1 The sum of the numbers in a sequence .

import functools
​
list1 = [1, 2, 3, 4, 5]
​
​
def func(a, b):
   return a + b
​
​
result = functools.reduce(func, list1)
​
print(result)  # 15

filter()

filter(func, lst) Function to filter the sequence , Filter out the elements that do not meet the conditions , Return to one filter object . If you want to convert to a list , have access to list() To convert .

list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
​
​
def func(x):
   return x % 2 == 0
​
​
result = filter(func, list1)
​
print(result)  # <filter object at 0x0000017AF9DC3198>
print(list(result))  # [2, 4, 6, 8, 10]

summary

  • recursive

    • The function itself calls itself

    • There must be an exit

  • lambda

    • grammar

    lambda parameter list : expression 
    • lambda The parametric form of

      • No parameter

      lambda: expression 
      • One parameter

      lambda Parameters : expression 
      • Default parameters

      lambda key=value: expression 
      • Variable length position parameters

      lambda *args: expression 
      • Variable length keyword parameter

      lambda **kwargs: expression 
  • Higher order function

    • effect : Pass in the function as an argument , Simplify the code

    • Built in higher order function

      • map()

      • reduce()

      • filter()

File operations

The role of file manipulation

reflection : What is a document ?

reflection : What does a file operation contain ?

answer : open 、 close 、 read 、 Write 、 Copy ....

reflection : What is the function of file operation ?

answer : Read the content 、 Write content 、 Backup content ......

summary : The function of file operation is == Put some content ( data ) Store , It can be used directly the next time the program is executed , Instead of having to make a new one , Time saving and labor saving ==.

The basic operation of the file

File operation steps

  1. Open file

  2. Read, write, etc

  3. Close file

Be careful : You can just open and close files , No read and write operations .

open

stay python, Use open function , You can open an existing file , Or create a new file , The grammar is as follows :

open(name, mode)

name: Is the string of the target file name to open ( It can contain the specific path where the file is located ).

mode: Set the mode to open the file ( Access pattern ): read-only 、 write in 、 Supplemental .

Open file mode

Pattern describe
r Open the file read-only . The pointer to the file will be placed at the beginning of the file . This is the default mode .
rb Open a file in binary format for read-only use . The file pointer will be placed at the beginning of the file . This is the default mode .
r+ Open a file for reading and writing . The file pointer will be placed at the beginning of the file .
rb+ Open a file in binary format for reading and writing . The file pointer will be placed at the beginning of the file .
w Open a file only for writing . Open the file if it already exists , And edit from the beginning , The original content will be deleted . If the file does not exist , Create a new file .
wb Opening a file in binary format is only used for writing . Open the file if it already exists , And edit from the beginning , The original content will be deleted . If the file does not exist , Create a new file .
w+ Open a file for reading and writing . Open the file if it already exists , And edit from the beginning , The original content will be deleted . If the file does not exist , Create a new file .
wb+ Open a file in binary format for reading and writing . Open the file if it already exists , And edit from the beginning , The original content will be deleted . If the file does not exist , Create a new file .
a Open a file for appending . If the file already exists , The file pointer will be placed at the end of the file . in other words , The new content will be written after the existing content . If the file does not exist , Create a new file to write to .
ab Open a file in binary format for appending . If the file already exists , The file pointer will be placed at the end of the file . in other words , The new content will be written after the existing content . If the file does not exist , Create a new file to write to .
a+ Open a file for reading and writing . If the file already exists , The file pointer will be placed at the end of the file . Append mode when the file opens . If the file does not exist , Create a new file for reading and writing .
ab+ Open a file in binary format for appending . If the file already exists , The file pointer will be placed at the end of the file . If the file does not exist , Create a new file for reading and writing .

Quick experience

f = open('test.txt', 'w')

Be careful : At this time f yes open File object for function .

File object method

  Write

  • grammar

 Object object .write(' Content ')
  • Experience

# 1. Open file
f = open('test.txt', 'w')
​
# 2. File is written to
f.write('hello world')
​
# 3. Close file
f.close()

Be careful :

  1. w and a Pattern : Create the file if it does not exist ; If the file exists ,w The mode is cleared before writing ,a Append directly to the end of the mode .

  2. r Pattern : If the file does not exist, an error is reported .

  read

  • read()

 File object .read(num)

num Represents the length of data to read from the file ( Unit is byte ), If no incoming num, That means reading all the data in the file .

  • readlines()

readlines The contents of the whole file can be read at one time in the form of lines , And it returns a list , The data in each row is an element .

f = open('test.txt')
content = f.readlines()
​
# ['hello world\n', 'abcdefg\n', 'aaa\n', 'bbb\n', 'ccc']
print(content)
​
# Close file
f.close()

  • readline()

readline() Read one line at a time .

f = open('test.txt')
​
content = f.readline()
print(f' first line :{content}')
​
content = f.readline()
print(f' The second line :{content}')
​
# Close file
f.close()

seek()

effect : Used to move the file pointer .

The grammar is as follows :

 File object .seek( Offset , The starting position )

The starting position :

  • 0: Beginning of file

  • 1: The current position

  • 2: End of file

close

 File object .close()

File backup

demand : The user enters any file name in the current directory , The program completes the backup function of the file ( The backup file name is xx[ Backup ] suffix , for example :test[ Backup ].txt).

step

  1. Receive the file name entered by the user

  2. Plan the backup file name

  3. Backup file write data

Code implementation

  1. Receive user input destination file name

old_name = input(' Please enter the file name you want to back up :')

  1. Plan the backup file name

    2.1 Extract destination file suffix

    2.2 File name of the organization backup ,xx[ Backup ] suffix

# 2.1 Extract the subscript of the suffix point of the file
index = old_name.rfind('.')
​
# print(index) # In suffix . The subscript
​
# print(old_name[:index]) # The source file name ( no suffix )
​
# 2.2 Organize new file names Old filename + [ Backup ] + suffix
new_name = old_name[:index] + '[ Backup ]' + old_name[index:]
​
# Print new file name ( With suffix )
# print(new_name)
  1. Backup file write data

    3.1 open the source file and Backup file

    3.2 Write source file data to backup file

    3.3 Close file

# 3.1 Open file
old_f = open(old_name, 'rb')
new_f = open(new_name, 'wb')
​
# 3.2 Write source file data to backup file
while True:
   con = old_f.read(1024)
   if len(con) == 0:
       break
   new_f.write(con)
​
# 3.3 Close file
old_f.close()
new_f.close()

reflection

If user input .txt, This is an invalid file , How can the program be changed to limit that only valid file names can be backed up ?

answer : Add condition judgment .

old_name = input(' Please enter the file name you want to back up :')
​
index = old_name.rfind('.')
​
​
if index > 0:
   postfix = old_name[index:]
​
new_name = old_name[:index] + '[ Backup ]' + postfix
​
old_f = open(old_name, 'rb')
new_f = open(new_name, 'wb')
​
while True:
   con = old_f.read(1024)
   if len(con) == 0:
       break
   new_f.write(con)
​
old_f.close()
new_f.close()

File and folder operations

stay Python The operation of files and folders in the os Related functions in the module , The specific steps are as follows :

  1. Import os modular

import os
  1. Use os Module related functions

os. Function name ()

File rename

os.rename( Destination filename , New file name )

Delete file

os.remove( Destination filename )

Create folder

os.mkdir( Folder name )

Delete folder

os.rmdir( Folder name )

Get current directory

os.getcwd()

Change the default directory

os.chdir( Catalog )

  Get directory list

os.listdir( Catalog )

The application case

demand : Batch modify file name , You can add a specified string , It can also delete the specified string .

  • step

  1. Sets the identity of the string to be added or deleted

  2. Gets all files in the specified directory

  3. Add existing file name / Delete the specified string , Construct a new name

  4. os.rename() rename

  • Code

import os
​
# Set rename ID : If 1 The specified character is added ,flag The value is 2 The specified character is deleted
flag = 1
​
# Get the specified directory
dir_name = './'
​
# Gets the list of files in the specified directory
file_list = os.listdir(dir_name)
# print(file_list)
​
​
# Traverse the files in the file list
for name in file_list:
​
   # Add specified character
   if flag == 1:
       new_name = 'Python-' + name
   # Delete specified characters
   elif flag == 2:
       num = len('Python-')
       new_name = name[num:]
​
   # Print new file name , Test program correctness
   print(new_name)
   
   # rename
   os.rename(dir_name+name, dir_name+new_name)

summary

  • File operation steps

    • open

     File object = open( Target file , Access pattern )
    • operation

      • read

       File object .read()
      File object .readlines()
      File object .readline()
      • Write

       File object .write()
      • seek()

    • close

     File object .close()
  • Primary access mode

    • w: Write , If the file does not exist, create a new file

    • r: read , If the file does not exist, an error will be reported

    • a: Additional

  • File and folder operations

    • rename :os.rename()

    • Get current directory :os.getcwd()

    • Get directory list :os.listdir()

Object oriented fundamentals

Understand object orientation

Object oriented is an abstract programming idea , There is an idea in many programming languages .

summary :== Object oriented is to treat programming as a thing , For the outside world , Things are used directly , Don't worry about his internal situation . Programming is about setting what things can do .==

Classes and objects

In the process of object-oriented programming , There are two important components : class   and object

The relationship between classes and objects : Use class to create an object .

Understand classes and objects

class

Class is a class that has the same == features == and == Behavior == A general term for things , It's a == Abstract concept ==, Something that is not real .

  • Characteristics are attributes

  • Behavior is method

object

Objects are real things created by classes

Be careful : In development , Prior class , Another object .

Object oriented implementation method

Defining classes

Python2 The middle class is divided into : Classic class and The new class

  • grammar

class Class name ():
    Code
  ......

Be careful : The class name shall meet the identifier naming rules , Follow at the same time == Naming habit of big hump ==.

  • Experience

class Washer():
   def wash(self):
       print(' I can wash clothes ')
  • expand : Classic class

Classes that are not derived from any built-in type , Call it the classic class

class Class name :
    Code
  ......

Create objects

Object, also known as instance .

  • grammar

 Object name = Class name ()
  • Experience

# Create objects
haier1 = Washer()
​
# <__main__.Washer object at 0x0000018B7B224240>
print(haier1)
​
# haier Object calls instance methods
haier1.wash()

Be careful : The process of creating objects is also called instantiating objects .

self

self Refers to the object that calls the function .

# 1. Defining classes
class Washer():
   def wash(self):
       print(' I can wash clothes ')
       # <__main__.Washer object at 0x0000024BA2B34240>
       print(self)
​
​
# 2. Create objects
haier1 = Washer()
# <__main__.Washer object at 0x0000018B7B224240>
print(haier1)
# haier1 Object calls instance methods
haier1.wash()
​
​
haier2 = Washer()
# <__main__.Washer object at 0x0000022005857EF0>
print(haier2)

Be careful : Print objects and self The results are consistent , Are the memory storage addresses of the current object .

Add and get object properties

Object properties can be added and obtained outside the class , It can also be added and obtained in the class .

Add object attribute syntax outside class

 Object name . Property name = value 
  • Experience

haier1.width = 500
haier1.height = 800

Get object properties outside class

  • grammar

 Object name . Property name 
  • Experience

print(f'haier1 What is the width of the washing machine {haier1.width}')
print(f'haier1 What is the height of the washing machine {haier1.height}')

Class to get object properties

  • grammar

self. Property name 
  • Experience

# Defining classes
class Washer():
   def print_info(self):
       # Class to get instance properties
       print(f'haier1 What is the width of the washing machine {self.width}')
       print(f'haier1 What is the height of the washing machine {self.height}')
​
# Create objects
haier1 = Washer()
​
# Add instance properties
haier1.width = 500
haier1.height = 800
​
haier1.print_info()

Magic methods

stay Python in ,__xx__() The function of is called magic method , Refers to functions with special functions .

__init__()

Experience __init__()

==__init__() The role of methods : Initialize object .==

class Washer():
   
   # Functions that define initialization functions
   def __init__(self):
       # Add instance properties
       self.width = 500
       self.height = 800
​
​
   def print_info(self):
       # Class to call instance properties
       print(f' What is the width of the washing machine {self.width}, Height is {self.height}')
​
​
haier1 = Washer()
haier1.print_info()

Be careful :

  • __init__() Method , Called by default when an object is created , There is no need to manually call

  • __init__(self) Medium self Parameters , No need for developers to deliver ,python The interpreter will automatically pass the current object reference to the past .

Parameterized __init__()

reflection : A class can create multiple objects , How to set different initialization properties for different objects ?

answer : The parameter .

class Washer():
   def __init__(self, width, height):
       self.width = width
       self.height = height
​
   def print_info(self):
       print(f' What is the width of the washing machine {self.width}')
       print(f' What is the height of the washing machine {self.height}')
​
​
haier1 = Washer(10, 20)
haier1.print_info()
​
​
haier2 = Washer(30, 40)
haier2.print_info()

__str__()

When using print When outputting objects , The memory address of the default print object . If the class defines __str__ Method , Then it will print from in this method return The data of .

class Washer():
   def __init__(self, width, height):
       self.width = width
       self.height = height
​
   def __str__(self):
       return ' This is the instruction manual of Haier washing machine '
​
​
haier1 = Washer(10, 20)
# This is the instruction manual of Haier washing machine
print(haier1)

__del__()

When deleting objects ,python The interpreter will also call by default __del__() Method .

class Washer():
   def __init__(self, width, height):
       self.width = width
       self.height = height
​
   def __del__(self):
       print(f'{self} Object has been deleted ')
​
​
haier1 = Washer(10, 20)
​
# <__main__.Washer object at 0x0000026118223278> Object has been deleted
del haier1

Comprehensive application

Roasted sweet potatoes

  demand

Demand main line :

  1. Roasted time and corresponding sweet potato state :

    0-3 minute : raw

    3-5 minute : Halfcooked

    5-8 minute : Cooked

    exceed 8 minute : It's burnt

  2. Seasoning added :

    Users can add spices according to their wishes

Step analysis

Requirements involve one thing : Sweet potatoes , So the case involves a class : Sweet potato .

5.1.2.1 Defining classes

  • Properties of sweet potato

    • Baking time

    • State of sweet potato

    • Seasoning added

  • Method for producing sweet potato

    • Roasted

      • The user sets the time for each roast of sweet potato according to their wishes

      • Judge the total time when sweet potatoes are roasted , Modify sweet potato status

    • Add seasoning

      • You can set the seasoning to be added according to your wishes

      • Store the seasoning added by the user

  • Display object information

5.1.2.2 Create objects , Call related instance methods

Code implementation

5.1.3.1 Defining classes

  • Sweet potato attribute

    • Define sweet potato initialization properties , Later, update instance properties according to the program

class SweetPotato():
   def __init__(self):
       # Baking time
       self.cook_time = 0
       # State of sweet potato
       self.cook_static = ' raw '
       # Seasoning list
       self.condiments = []

5.1.3.2 Define how to roast sweet potato

class SweetPotato():
  ......
   
   def cook(self, time):
       """ Method for roasting sweet potato """
       self.cook_time += time
       if 0 <= self.cook_time < 3:
           self.cook_static = ' raw '
       elif 3 <= self.cook_time < 5:
           self.cook_static = ' Halfcooked '
       elif 5 <= self.cook_time < 8:
           self.cook_static = ' Ripe '
       elif self.cook_time >= 8:
           self.cook_static = ' It's burnt '

5.1.3.3 Writing str Magic methods , Used to output object status

class SweetPotato():
......
​
   def __str__(self):
       return f' This sweet potato is roasted {self.cook_time} minute , Status is {self.cook_static}'
​

5.1.3.4 Create objects , Test instance properties and instance methods

digua1 = SweetPotato()
print(digua1)
digua1.cook(2)
print(digua1)

5.1.3.5 Define adding seasoning method , And call the instance method

class SweetPotato():
......
​
   def add_condiments(self, condiment):
       """ Add seasoning """
       self.condiments.append(condiment)
   def __str__(self):
       return f' This sweet potato is roasted {self.cook_time} minute , Status is {self.cook_static}, The spices added are {self.condiments}'
     
​
digua1 = SweetPotato()
print(digua1)
​
digua1.cook(2)
digua1.add_condiments(' The soy sauce ')
print(digua1)
​
digua1.cook(2)
digua1.add_condiments(' chili powder ')
print(digua1)
​
digua1.cook(2)
print(digua1)
​
digua1.cook(2)
print(digua1)

Code Overview

# Defining classes
class SweetPotato():
   def __init__(self):
       # Baking time
       self.cook_time = 0
       # State of sweet potato
       self.cook_static = ' raw '
       # Seasoning list
       self.condiments = []
​
   def cook(self, time):
       """ Method for roasting sweet potato """
       self.cook_time += time
       if 0 <= self.cook_time < 3:
           self.cook_static = ' raw '
       elif 3 <= self.cook_time < 5:
           self.cook_static = ' Halfcooked '
       elif 5 <= self.cook_time < 8:
           self.cook_static = ' Ripe '
       elif self.cook_time >= 8:
           self.cook_static = ' It's burnt '
​
   def add_condiments(self, condiment):
       """ Add seasoning """
       self.condiments.append(condiment)
​
   def __str__(self):
       return f' This sweet potato is roasted {self.cook_time} minute , Status is {self.cook_static}, The spices added are {self.condiments}'
​
​
digua1 = SweetPotato()
print(digua1)
​
digua1.cook(2)
digua1.add_condiments(' The soy sauce ')
print(digua1)
​
digua1.cook(2)
digua1.add_condiments(' chili powder ')
print(digua1)
​
digua1.cook(2)
print(digua1)
​
digua1.cook(2)
print(digua1)

Move furniture

demand

Put furniture smaller than the remaining area of the house into the house

Step analysis

Requirements involve two things : house and furniture , Therefore, the case involved two categories : Houses and Furniture .

5.2.2.1 Defining classes

  • Houses

    • Instance attributes

      • House location

      • Floor area of the house

      • Remaining area of house

      • List of furniture in the house

    • Example method

      • Accommodating furniture

    • Display house information

  • Furniture

    • Furniture name

    • Furniture floor area

5.2.2.2 Create an object and call related methods

Code implementation

5.2.3.1 Defining classes

  • Furniture

class Furniture():
   def __init__(self, name, area):
       # Furniture name
       self.name = name
       # Furniture floor area
       self.area = area

  • Houses

class Home():
   def __init__(self, address, area):
       # Location
       self.address = address
       # Building area
       self.area = area
       # The remaining area
       self.free_area = area
       # Furniture list
       self.furniture = []
​
   def __str__(self):
       return f' The house is located in {self.address}, Covers an area of {self.area}, The remaining area {self.free_area}, Furniture has {self.furniture}'
​
   def add_furniture(self, item):
       """ Accommodating furniture """
       if self.free_area >= item.area:
           self.furniture.append(item.name)
           # After the furniture is moved in , Remaining area of house = Previous remaining area - The furniture area
           self.free_area -= item.area
       else:
           print(' The furniture is too big , Insufficient remaining area , Can't hold ')

Create an object and call instance properties and methods

bed = Furniture(' Double bed ', 6)
jia1 = Home(' Beijing ', 1200)
print(jia1)
​
jia1.add_furniture(bed)
print(jia1)
​
sofa = Furniture(' Sofa ', 10)
jia1.add_furniture(sofa)
print(jia1)
​
ball = Furniture(' Basketball Court ', 1500)
jia1.add_furniture(ball)
print(jia1)

summary

  • An important part of object-oriented

    • class

      • Create a class

    class Class name ():
      Code 
    • object

     Object name = Class name ()
  • Add object properties

    • Out of class

     Object name . Property name = value 
    • In class

    self. Property name = value 
  • Get object properties

    • Out of class

     Object name . Property name 
    • In class

    self. Property name 
  • Magic methods

    • __init__(): initialization

    • __str__(): Output object information

    • __del__(): Called when an object is deleted

object-oriented - Inherit

Concept of inheritance

Inheritance in life , Generally speaking, children inherit the property of their parents .

  • expand 1: Classic class or old style class

Classes that are not derived from any built-in type , Call it the classic class .

class Class name :
    Code
  ......
  • expand 2: The new class

class Class name (object):
  Code 

Python Object oriented inheritance refers to the relationship between multiple classes , That is, the child class inherits all the properties and methods of the parent class by default , As follows :

# Parent class A
class A(object):
   def __init__(self):
       self.num = 1
​
   def info_print(self):
       print(self.num)
​
# Subclass B
class B(A):
   pass
​
​
result = B()
result.info_print()  # 1

stay Python in , All classes inherit by default object class ,object A class is a top-level class or a base class ; Other subclasses are called derived classes .

Single inheritance

The main line of the story : A pancake and fruit teacher , I've been in the pancake industry for many years , Developed a set of exquisite techniques for spreading pancakes and fruits . Master wants to teach this technique to his only and most proud apprentice .

analysis : Does the apprentice want to inherit all the master's skills ?

# 1. Master class
class Master(object):
   def __init__(self):
       self.kongfu = '[ Old recipe for pancakes and fruit ]'
​
   def make_cake(self):
       print(f' Application {self.kongfu} Make pancakes and fruit ')
​
       
# 2. Apprentice class
class Prentice(Master):
   pass
​
​
# 3. Create objects daqiu
daqiu = Prentice()
# 4. Object access instance properties
print(daqiu.kongfu)
# 5. Object calls instance methods
daqiu.make_cake()

Multiple inheritance

The story advances : Xiao Ming is a good boy who loves learning , I want to learn more about pancake fruit technology , therefore , Search and learn in Baidu

The so-called multiple inheritance means that a class inherits more than one parent class at the same time .

class Master(object):
   def __init__(self):
       self.kongfu = '[ Old recipe for pancakes and fruit ]'
​
   def make_cake(self):
       print(f' Application {self.kongfu} Make pancakes and fruit ')
​
​
# Create a school class
class School(object):
   def __init__(self):
       self.kongfu = '[ Pancake fruit formula ]'
​
   def make_cake(self):
       print(f' Application {self.kongfu} Make pancakes and fruit ')
​
​
class Prentice(School, Master):
   pass
​
​
daqiu = Prentice()
print(daqiu.kongfu)
daqiu.make_cake()

Be careful : When a class has more than one parent class , By default, the properties and methods with the same name of the first parent class are used .

Subclasses override methods and properties with the same name as the parent class

The story : After Xiaoming has mastered the skills of master and training , I devote myself to develop my own unique recipe of a set of new pancake fruit technology .

class Master(object):
   def __init__(self):
       self.kongfu = '[ Old recipe for pancakes and fruit ]'
​
   def make_cake(self):
       print(f' Application {self.kongfu} Make pancakes and fruit ')
​
​
class School(object):
   def __init__(self):
       self.kongfu = '[ Pancake fruit formula ]'
​
   def make_cake(self):
       print(f' Application {self.kongfu} Make pancakes and fruit ')
​
​
# Original formula
class Prentice(School, Master):
   def __init__(self):
       self.kongfu = '[ Original recipe for pancakes and fruits ]'
​
   def make_cake(self):
       print(f' Application {self.kongfu} Make pancakes and fruit ')
​
​
daqiu = Prentice()
print(daqiu.kongfu)
daqiu.make_cake()
​
print(Prentice.__mro__)

Subclasses and superclasses have the same properties and methods , By default, subclass properties and methods with the same name are used .

The subclass calls the methods and properties of the parent class with the same name

The story : Many customers would like to have pancakes made of ancient French and black horse techniques .

class Master(object):
   def __init__(self):
       self.kongfu = '[ Old recipe for pancakes and fruit ]'
​
   def make_cake(self):
       print(f' Application {self.kongfu} Make pancakes and fruit ')
​
​
class School(object):
   def __init__(self):
       self.kongfu = '[ Black horse pancake fruit formula ]'
​
   def make_cake(self):
       print(f' Application {self.kongfu} Make pancakes and fruit ')
​
​
class Prentice(School, Master):
   def __init__(self):
       self.kongfu = '[ Original recipe for pancakes and fruits ]'
​
   def make_cake(self):
       # If the parent class's properties and methods are called first , The parent property will override the class property , So before calling properties , First call your own subclass initialization
       self.__init__()
       print(f' Application {self.kongfu} Make pancakes and fruit ')
​
   # Call the superclass method , However, in order to ensure that the properties of the parent class are also called , You must call the initialization of the parent class before calling the method
   def make_master_cake(self):
       Master.__init__(self)
       Master.make_cake(self)
​
   def make_school_cake(self):
       School.__init__(self)
       School.make_cake(self)
​
​
daqiu = Prentice()
​
daqiu.make_cake()
​
daqiu.make_master_cake()
​
daqiu.make_school_cake()
​
daqiu.make_cake()

Multiple inheritance

The story :N After year , Xiao Ming is old , Want to pass on all the technology to his apprentice .

class Master(object):
   def __init__(self):
       self.kongfu = '[ Old recipe for pancakes and fruit ]'
​
   def make_cake(self):
       print(f' Application {self.kongfu} Make pancakes and fruit ')
​
​
class School(object):
   def __init__(self):
       self.kongfu = '[ Pancake fruit formula ]'
​
   def make_cake(self):
       print(f' Application {self.kongfu} Make pancakes and fruit ')
​
​
class Prentice(School, Master):
   def __init__(self):
       self.kongfu = '[ Original recipe for pancakes and fruits ]'
​
   def make_cake(self):
       self.__init__()
       print(f' Application {self.kongfu} Make pancakes and fruit ')
​
   def make_master_cake(self):
       Master.__init__(self)
       Master.make_cake(self)
​
   def make_school_cake(self):
       School.__init__(self)
       School.make_cake(self)
​
​
# Grandsons
class Tusun(Prentice):
   pass
​
​
xiaoqiu = Tusun()
​
xiaoqiu.make_cake()
​
xiaoqiu.make_school_cake()
​
xiaoqiu.make_master_cake()
​

super() Call the superclass method

class Master(object):
   def __init__(self):
       self.kongfu = '[ Old recipe for pancakes and fruit ]'
​
   def make_cake(self):
       print(f' Application {self.kongfu} Make pancakes and fruit ')
​
​
class School(Master):
   def __init__(self):
       self.kongfu = '[ Pancake fruit formula ]'
​
   def make_cake(self):
       print(f' Application {self.kongfu} Make pancakes and fruit ')
​
       # Method 2.1
       # super(School, self).__init__()
       # super(School, self).make_cake()
​
       # Method 2.2
       super().__init__()
       super().make_cake()
​
​
class Prentice(School):
   def __init__(self):
       self.kongfu = '[ Unique pancake fruit technology ]'
​
   def make_cake(self):
       self.__init__()
       print(f' Application {self.kongfu} Make pancakes and fruit ')
​
   # The subclass calls the methods and properties of the parent class with the same name : Encapsulate the property and method with the same name of the parent class again
   def make_master_cake(self):
       Master.__init__(self)
       Master.make_cake(self)
​
   def make_school_cake(self):
       School.__init__(self)
       School.make_cake(self)
​
   # Call the same name property and method of the parent class at one time
   def make_old_cake(self):
       # Method 1 : Code redundancy ; If the parent class name changes , The code needs to be modified frequently
       # Master.__init__(self)
       # Master.make_cake(self)
       # School.__init__(self)
       # School.make_cake(self)
​
       # Method 2 : super()
       # Method 2.1 super( The name of the class , self). function ()
       # super(Prentice, self).__init__()
       # super(Prentice, self).make_cake()
​
       # Method 2.2 super(). function ()
       super().__init__()
       super().make_cake()
​
​
daqiu = Prentice()
​
daqiu.make_old_cake()

Be careful : Use super() You can automatically find the parent class . The call order follows __mro__ The order of class properties . It is suitable for single inheritance .

Private rights

Define private properties and methods

stay Python in , You can set private permissions for instance properties and methods , That is to set an instance property or instance method not to inherit to subclass .

The story : While Xiao Ming passed on his technology to his apprentice , Don't want to put your money (2000000 $ ) Inherit to the apprentice , This is the time for money This instance property sets private permissions .

How to set private permissions : In the property name and method name front Add two underscores __.

class Master(object):
   def __init__(self):
       self.kongfu = '[ Old recipe for pancakes and fruit ]'
​
   def make_cake(self):
       print(f' Application {self.kongfu} Make pancakes and fruit ')
​
​
class School(object):
   def __init__(self):
       self.kongfu = '[ Pancake fruit formula ]'
​
   def make_cake(self):
       print(f' Application {self.kongfu} Make pancakes and fruit ')
​
​
class Prentice(School, Master):
   def __init__(self):
       self.kongfu = '[ Original recipe for pancakes and fruits ]'
       # Define private properties
       self.__money = 2000000
​
   # Define private methods
   def __info_print(self):
       print(self.kongfu)
       print(self.__money)
​
   def make_cake(self):
       self.__init__()
       print(f' Application {self.kongfu} Make pancakes and fruit ')
​
   def make_master_cake(self):
       Master.__init__(self)
       Master.make_cake(self)
​
   def make_school_cake(self):
       School.__init__(self)
       School.make_cake(self)
​
​
# Grandsons
class Tusun(Prentice):
   pass
​
​
daqiu = Prentice()
# Objects cannot access private properties and methods
# print(daqiu.__money)
# daqiu.__info_print()
​
xiaoqiu = Tusun()
# Subclasses cannot inherit private properties and methods of the parent class
# print(xiaoqiu.__money) # Unable to access instance properties __money
# xiaoqiu.__info_print()

Be careful : Private properties and methods can only be accessed and modified in the class .

  Get and modify private property values

stay Python in , General definition function name get_xx Used to get private properties , Definition set_xx Used to modify private property values .

class Master(object):
   def __init__(self):
       self.kongfu = '[ Old recipe for pancakes and fruit ]'
​
   def make_cake(self):
       print(f' Application {self.kongfu} Make pancakes and fruit ')
​
​
class School(object):
   def __init__(self):
       self.kongfu = '[ Pancake fruit formula ]'
​
   def make_cake(self):
       print(f' Application {self.kongfu} Make pancakes and fruit ')
​
​
class Prentice(School, Master):
   def __init__(self):
       self.kongfu = '[ Original recipe for pancakes and fruits ]'
       self.__money = 2000000
​
   # Get private properties
   def get_money(self):
       return self.__money
​
   # Modify private properties
   def set_money(self):
       self.__money = 500
​
   def __info_print(self):
       print(self.kongfu)
       print(self.__money)
​
   def make_cake(self):
       self.__init__()
       print(f' Application {self.kongfu} Make pancakes and fruit ')
​
   def make_master_cake(self):
       Master.__init__(self)
       Master.make_cake(self)
​
   def make_school_cake(self):
       School.__init__(self)
       School.make_cake(self)
​
​
# Grandsons
class Tusun(Prentice):
   pass
​
​
daqiu = Prentice()
​
xiaoqiu = Tusun()
# call get_money Function to get private properties money Value
print(xiaoqiu.get_money())
# call set_money Function to modify private properties money Value
xiaoqiu.set_money()
print(xiaoqiu.get_money())

summary

  • The characteristics of inheritance

    • By default, a subclass has all the properties and methods of its parent class

    • Subclasses override methods and properties with the same name as the parent class

    • The subclass calls the methods and properties with the same name of the parent class

  • super() Method to quickly call the parent method

  • Private rights

    • Properties and methods that cannot be inherited to subclasses need to add private permissions

    • grammar

    class Class name ():
     # Private property
     __ Property name = value
    ​
     # Private method
     def __ Function name (self):
        Code
    

object-oriented - other  

Three characteristics of object-oriented

  • encapsulation

    • The operation of writing properties and methods into a class is encapsulation

    • Encapsulation can add private permissions to properties and methods

  • Inherit

    • The subclass inherits all the properties and methods of the parent class by default

    • Subclasses can override parent class properties and methods

  • polymorphic

    • Pass in different objects , It produces different results

polymorphic

Understanding polymorphism

Polymorphism means that a kind of thing has many forms ,( An abstract class has many subclasses , So the concept of polymorphism depends on inheritance ).

  • Definition : Polymorphism is a way of using objects , Subclass override parent method , Call the same parent method of different subclass objects , Different execution results can be produced

  • benefits : Flexible call , With polymorphism , Easier to write generic code , Make general programming , To adapt to the changing needs !

  • Implementation steps :

    • Define parent class , And provide public methods

    • Defining subclasses , And override the parent class method

    • Pass the subclass object to the caller , You can see that different subclasses have different execution effects

Experience polymorphism

class Dog(object):
   def work(self):  # The parent class provides a unified method , Even empty methods
       print(' Where to hit ...')
​
​
class ArmyDog(Dog):  # Inherit Dog class
   def work(self):  # Subclasses override methods with the same name as parent classes
       print(' follow up the enemy ...')
​
​
class DrugDog(Dog):
   def work(self):
       print(' Trace drugs ...')
​
​
class Person(object):
   def work_with_dog(self, dog):  # Pass in different objects , Execute different code , That's different work function
       dog.work()
​
​
ad = ArmyDog()
dd = DrugDog()
​
daqiu = Person()
daqiu.work_with_dog(ad)
daqiu.work_with_dog(dd)

Class properties and instance properties

Class properties

Setting and accessing class properties

  • Class properties are Class object The attributes that you have , It has been All instance objects of this class All in all .

  • Class properties can be used Class object or Instance object visit .

class Dog(object):
   tooth = 10
​
​
wangcai = Dog()
xiaohei = Dog()
​
print(Dog.tooth)  # 10
print(wangcai.tooth)  # 10
print(xiaohei.tooth)  # 10

Advantages of class properties

  • Recorded data Always consistent , Class properties are defined .

  • Instance attributes requirement Each object For its Open up a separate memory space To record data , and Class properties Shared by the whole class , Only one share of memory is used , More memory saving .

Modify class properties

Class properties can only be modified through class objects , Cannot be modified by an instance object , If you modify class properties through an instance object , Indicates that an instance property is created .

class Dog(object):
   tooth = 10
​
​
wangcai = Dog()
xiaohei = Dog()
​
# Modify class properties
Dog.tooth = 12
print(Dog.tooth)  # 12
print(wangcai.tooth)  # 12
print(xiaohei.tooth)  # 12
​
# Properties cannot be modified through objects , If you do this , In fact, an instance property is created
wangcai.tooth = 20
print(Dog.tooth)  # 12
print(wangcai.tooth)  # 20
print(xiaohei.tooth)  # 12

Instance attributes

class Dog(object):
   def __init__(self):
       self.age = 5
​
   def info_print(self):
       print(self.age)
​
​
wangcai = Dog()
print(wangcai.age)  # 5
# print(Dog.age) # Report errors : Instance properties cannot be accessed through classes
wangcai.info_print()  # 5

Class methods and static methods

Class method

Class method characteristics

  • Decorator required @classmethod To identify it as a class method , For class methods , The first parameter must be a class object , General with cls As the first parameter .

Class method usage scenario

  • When method Class objects are required ( Such as accessing private class properties, etc ) when , Define class methods

  • Class methods are generally used in conjunction with class properties

class Dog(object):
   __tooth = 10
​
   @classmethod
   def get_tooth(cls):
       return cls.__tooth
​
​
wangcai = Dog()
result = wangcai.get_tooth()
print(result)  # 10

Static methods

Static method characteristics

  • Need to go through the decorator @staticmethod To embellish , Static methods do not need to pass either class objects or instance objects ( No formal parameters self/cls).

  • Static methods Can also pass through Instance object and Class object To visit .

Static methods use scenarios

  • When method You do not need to use instance objects ( Such as instance object , Instance attributes ), There is no need to use class objects ( Such as class attribute 、 Class method 、 Create instances, etc ) when , Define static methods

  • Cancel unnecessary parameter passing , advantageous to Reduce unnecessary memory consumption and performance consumption

class Dog(object):
   @staticmethod
   def info_print():
       print(' This is a dog , Used to create dog instances ....')
​
​
wangcai = Dog()
# Static methods can be accessed using both objects and classes
wangcai.info_print()
Dog.info_print()

summary

  • Three characteristics of object-oriented

    • encapsulation

    • Inherit

    • polymorphic

  • Class properties

    • Attributes belonging to class objects , Properties common to all objects

  • Instance attributes

  • Class method

@classmethod
def xx():
  Code 
  • Static methods

@staticmethod
def xx():
  Code 

abnormal

Understanding anomalies

When an error is detected , The interpreter can't continue , On the contrary, there are some wrong hints , That's what's called " abnormal ".

for example : With r Open a nonexistent file in .

open('test.txt', 'r')

Abnormal writing

grammar

try:
    The code that could have an error
except:
    If there is an exception to the execution of the code 

Quick experience

demand : Try to r Mode open file , If the file doesn't exist , with w Mode on .

try:
   f = open('test.txt', 'r')
except:
   f = open('test.txt', 'w')

Catch the specified exception

grammar

try:
    The code that could have an error
except Exception types :
    If the code executed by this exception type is caught 

Experience

try:
   print(num)
except NameError:
   print(' Erroneous ')

Be careful :

  1. If the exception type of the code you are trying to execute is inconsistent with the exception type to catch , The exception cannot be caught .

  2. commonly try Below is just one line of code that you're trying to execute .

Catch multiple specified exceptions

When more than one exception is caught , The name of the exception type to be caught , Put it in except after , And use tuples to write .

try:
   print(1/0)
​
except (NameError, ZeroDivisionError):
   print(' Erroneous ')

Capture exception description information

try:
   print(num)
except (NameError, ZeroDivisionError) as result:
   print(result)

Catch all exceptions

Exception Is the parent of all program exception classes .

try:
   print(num)
except Exception as result:
   print(result)

Anomalous else

else Represents the code to execute if there are no exceptions .

try:
   print(1)
except Exception as result:
   print(result)
else:
   print(' I am a else, It is the code executed when there is no exception ')

Anomalous finally

finally Represents the code to be executed regardless of whether it is abnormal or not , For example, closing a file .

try:
   f = open('test.txt', 'r')
except Exception as result:
   f = open('test.txt', 'w')
else:
   print(' No abnormal , I'm so happy ')
finally:
   f.close()

The transmission of exceptions

Experience abnormal delivery

demand :

1. Try opening it read-only test.txt file , If the file exists, read the contents of the file , If the file does not exist, prompt the user .

2. Reading content requires : Try looping through the content , If an unexpected termination of the program is detected during the reading process , be except Catch exceptions and prompt the user .

import time
try:
   f = open('test.txt')
   try:
       while True:
           content = f.readline()
           if len(content) == 0:
               break
           time.sleep(2)
           print(content)
   except:
       # If in the process of reading a file , There was an exception , Then we'll capture
       # such as Press ctrl+c
       print(' Reading data terminated unexpectedly ')
   finally:
       f.close()
       print(' Close file ')
except:
   print(" There is no such document ")

Custom exception

stay Python in , The syntax for throwing a custom exception is raise Exception class object .

demand : Insufficient password length , Abnormal Report ( User enters password , If the length entered is insufficient 3 position , False report , That is, a custom exception is thrown , And catch the exception ).

# Custom exception classes , Inherit Exception
class ShortInputError(Exception):
   def __init__(self, length, min_len):
       self.length = length
       self.min_len = min_len
​
   # Set the description of the exception thrown
   def __str__(self):
       return f' The length you entered is {self.length}, No less than {self.min_len} Characters '
​
​
def main():
   try:
       con = input(' Please input a password :')
       if len(con) < 3:
           raise ShortInputError(len(con), 3)
   except Exception as result:
       print(result)
   else:
       print(' The password has been entered ')
​
​
main()

summary

  • Exception Syntax

try:
Code where exceptions can occur
except:
If there is an exception to the execution of the code
else:
No code executed abnormally
finally:
Code to execute whether or not there is an exception 
  • Capture exception

except Exception types :
Code
​
except Exception types as xx:
Code 
  • Custom exception

# 1. Custom exception classes
class Exception class name (Exception):
Code
   
   # Set the description of the exception thrown
   def __str__(self):
     return ...
​
​
# 2. Throw an exception
raise Exception class name ()
​
# Capture exception
except Exception...

Modules and packages

  modular

Python modular (Module), It's a Python file , With .py ending , Contains Python Object definition and Python sentence .

Modules can define functions , Classes and variables , Modules can also contain executable code .

The import module

How to import modules

  • import Module name

  • from Module name import Function name

  • from Module name import *

  • import Module name as Alias

  • from Module name import Function name as Alias

Detailed introduction of import method

import

  • grammar

# 1. The import module
import Module name
import Module name 1, Module name 2...
​
# 2. Call function
Module name . Function name ()
  • Experience

import math
print(math.sqrt(9))  # 3.0

 from..import..

  • grammar

from Module name import function 1, function 2, function 3...
  • Experience

from math import sqrt
print(sqrt(9))

 from .. import *

  • grammar

from Module name import *
  • Experience

from math import *
print(sqrt(9))

 as Define an alias

  • grammar

# Module definition alias
import Module name as Alias
​
# Feature definition alias
from Module name import function as Alias 
  • Experience

# Module aliases
import time as tt
​
tt.sleep(2)
print('hello')
​
# Feature alias
from time import sleep as sl
sl(2)
print('hello')

Making modules

stay Python in , Every Python Files can be used as a module , The name of the module is the name of the file . In other words, the user-defined module name must comply with the identifier naming rules .

Define modules

Create a new one Python file , Name it my_module1.py, And define testA function .

def testA(a, b):
   print(a + b)

Test module

In practice , When a developer finishes writing a module , In order to let the module achieve the desired effect in the project , The developer will be on his own py Add some test information to the file ., for example , stay my_module1.py Add test code to file .

def testA(a, b):
   print(a + b)
​
​
testA(1, 1)

here , Whether it's the current file , Or other files that have imported the module , It will be executed automatically when running testA Function call .

The solution is as follows :

def testA(a, b):
   print(a + b)
​
# Call this function only in the current file , Other imported files do not meet this condition , Do not perform testA Function call
if __name__ == '__main__':
   testA(1, 1)

Call module

import my_module1
my_module1.testA(1, 1)

matters needing attention

If you use from .. import .. or from .. import * When importing multiple modules , And the module has the function of the same name . When calling this function with the same name , What is called is the function of the later imported module .

  • Experience

# modular 1 Code
def my_test(a, b):
   print(a + b)
​
# modular 2 Code
def my_test(a, b):
   print(a - b)
 
# Import module and call function code
from my_module1 import my_test
from my_module2 import my_test
​
# my_test Functions are modules 2 The function in
my_test(1, 1)

Module positioning sequence

When importing a module ,Python The search order of the parser for the module location is :

  1. Current directory

  2. If not in the current directory ,Python Search in shell Variable PYTHONPATH Every directory under .

  3. If you can't find ,Python Will look at the default path .UNIX Next , The default path is /usr/local/lib/python/

The module search path is stored in system Modular sys.path variable . Variable contains the current directory ,PYTHONPATH And the default directory determined by the installation process .

  • Be careful

    • Do not duplicate your own file name with the existing module name , Otherwise, the module function cannot be used

    • Use from Module name import function When , If the function name is repeated , What is called is the last defined or imported function .

__all__

If a module file has __all__ Variable , When using from xxx import * Import time , Only elements in this list can be imported .

  • my_module1 Module code

__all__ = ['testA']
​
​
def testA():
   print('testA')
​
​
def testB():
   print('testB')
  • File code of the import module

from my_module1 import *
testA()
testB()

package

The package organizes the associated modules , Put it in the same folder , And create a folder named __init__.py file , So this folder is called a package .

Production package

[New] — [Python Package] — Enter the package name — [OK] — New function module ( Linked modules ).

Be careful : After creating a new package , Automatically created inside the package __init__.py file , This file controls the import behavior of the package .

Quick experience

  1. New package mypackage

  2. New module in package :my_module1 and my_module2

  3. The codes in the module are as follows

# my_module1
print(1)
​
​
def info_print1():
   print('my_module1')
# my_module2
print(2)
​
​
def info_print2():
   print('my_module2')

  Import package

Method 1

import Package name . Module name
​
Package name . Module name . The goal is 

Experience

import my_package.my_module1
​
my_package.my_module1.info_print1()

Method 2

Be careful : Must be in __init__.py Add... To the file __all__ = [], Controls the list of modules that are allowed to be imported .

from Package name import *
Module name . The goal is 

Experience

from my_package import *
​
my_module1.info_print1()

summary

  • Import module method

import Module name
​
from Module name import The goal is
​
from Module name import *
  • Import package

import Package name . Module name
​
from Package name import *
  • __all__ = [] : List of modules or functions that can be imported

Past highlights :


I use Python Changed ban Hua's boot password , After logging in again, I found her secret !
 

I use Python Collected the spatial data set of Banhua , In addition to meizhao, she found her other secret again !
 

Roommate single love class flower failed , I climbed a website and sent it to him for instant cure , Men's happiness is so simple 【 Once a day , Forget first love 】

版权声明
本文为[Five packs of spicy strips!]所创,转载请带上原文链接,感谢
https://pythonmana.com/2021/09/20210909161448787H.html

  1. Python - Programmation orientée objet - pratique (6)
  2. Python - Programmation orientée objet - réflexion hasattr, GetAttr, GetAttr, delattr
  3. Python - Programmation orientée objet - _Dict
  4. Python - pydantic (2) Modèle imbriqué
  5. Non-ASCII character ‘\xe5‘ in file kf1.py on line 4, but no encoding declared; see http://python.or
  6. python笔记(一)
  7. Non - ASCII character 'xe5' in file kf1.py on Line 4, but no Encoding declared;Voirhttp://python.or
  8. Notes Python (1)
  9. Talk about how JMeter executes Python scripts concurrently
  10. In Beijing, you can't see the moon in the Mid Autumn Festival. Draw a blood red moon in Python
  11. Un des pandas crée un objet
  12. Machine learning | unitary regression model Python practical case
  13. Draw a "Lollipop chart" with Excel and python
  14. Python uses scikit learn to calculate TF-IDF
  15. Getting started with Python Basics_ 3 conditional statements and iterative loops
  16. Python dynamic properties and features
  17. 云计算开发:Python内置函数-min()函数详解
  18. [Python skill] how to speed up loop operation and numpy array operation
  19. 雲計算開發:Python內置函數-min()函數詳解
  20. Développement de l'informatique en nuage: explication détaillée de la fonction intégrée python - min ()
  21. 从0起步学Python(附程序实例讲解)第1讲
  22. 从0起步学Python(附程序实例讲解)第1讲
  23. Apprendre Python à partir de 0 (avec des exemples de programme) leçon 1
  24. Apprendre Python à partir de 0 (avec des exemples de programme) leçon 1
  25. With Python, I'll take you to enjoy it for a month when the Mid Autumn Festival is coming
  26. You can't write interface software in Python! Which software on sale has no UI?
  27. Python国内外原题解析及源码1~15
  28. Python实现长篇英文自动纠错~
  29. Python implémente la correction automatique des erreurs en anglais long
  30. Analyse des problèmes originaux et code source de Python au pays et à l'étranger 1 ~ 15
  31. 一张思维导图学Python之表白
  32. Python教学中课程思政建设的研究探索2
  33. Recherche sur la construction idéologique et politique du Programme d'études dans l'enseignement Python 2
  34. Une présentation de la cartographie mentale Python
  35. Python高级用法总结(8)-函数式编程
  36. Python + Mirai development QQ robot starting tutorial (2021.9.9 test is valid)
  37. Python Advanced use Summary (8) - functional Programming
  38. How to get started with Python and share learning methods for free. All you want to know is here
  39. Python + Mirai development QQ robot starting tutorial (2021.9.9 test is valid)
  40. Python趣味编程中(PPT适合青少儿和零基础学习Python)
  41. Python基础第1讲(含代码、Python最新安装包、父与子的编程之旅:与小卡特一起学Python中文版)
  42. 用 Python 增强 Git
  43. Python基礎第1講(含代碼、Python最新安裝包、父與子的編程之旅:與小卡特一起學Python中文版)
  44. Base Python leçon 1 (y compris le Code, le dernier paquet d'installation Python, le voyage de programmation parent - enfant: apprendre la version chinoise de python avec le petit Carter)
  45. Dans la programmation amusante Python (ppt pour les jeunes enfants et l'apprentissage de base zéro Python)
  46. 非常好的题目详解Python字典的用法
  47. Python teaches you to build wechat push live Betta reminder from 0 (single room simplified version)
  48. Python 协程与 JavaScript 协程的对比
  49. 手把手带你用Python实现一个量化炒股策略
  50. Main dans la main pour mettre en œuvre une stratégie quantitative de spéculation boursière en python
  51. Comparaison des coproductions Python et JavaScript
  52. 【python种子项目ppc】一行代码生成项目与开发详细指导
  53. Docker 部署一个用 Python 编写的 Web 应用
  54. Python - poetry(4)管理环境
  55. Python - poetry(2)命令介绍
  56. [Python Seed Project PPC] a line of Code Generation Project and Development detailed guidance
  57. Introduction à la commande python - Poetry (2)
  58. Python - Poetry (4) Management Environment
  59. I collected Banhua's spatial data set in Python. In addition to meizhao, I found her other secrets again!
  60. I modified ban Hua's boot password in Python and found her secret after logging in again!