程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Getting started with Python

編輯:Python

Python

Appoint python Interpreter and encoding method

#!/usr/bin/python
# -*- coding: UTF-8 -*-

One 、 Basic grammar

1. code

  • code : Convert human readable characters into machine readable bytecodes / Byte sequence
  • decode : The reverse process of encoding is called decoding
  • summary :Unicode Is a human readable character format ;ASCIIUTF-8GBK And so on are byte code formats that can be recognized by the machine . We wrote in the document py3 Code , Is composed of characters , Their format , Namely Unicode, Characters are stored in files in bytes , The file is saved in memory / In physical disk .

Python2 The default encoding for is ASCII, Cannot recognize Chinese characters , You need to explicitly specify the character encoding

Python3 The default encoding for is Unicode, Can recognize Chinese characters

Data in computer memory , Unified use Unicode code

Data transfer or save to hard disk , Use UTF-8 code

# Specify a different encoding for the source file , At the beginning, it reads as follows :
# -*- coding:utf-8 -*-

2. identifier

  • The first character must be a letter or underscore in the alphabet _ .
  • The rest of the identifier consists of the letters 、 Numbers and underscores .
  • identifier Case sensitive .

stay Python 3 in , You can use Chinese as the variable name , Not ASCII Identifiers are also allowed .

3. keyword

Reserved words are keywords , We can't use them as any identifier names .Python The standard library of provides a keyword modular , You can output all keywords of the current version :

>>> import keyword
>>> keyword.kwlist
['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

4. notes

Appoint Python Interpreter

#!/usr/bin/python3
# Single-line comments 
print ("Hello, Python!") # The second note 
''' The third note Fourth note '''
""" Fifth note Sixth note """

5. Lines and indents

python The most distinctive feature is the use of indentation to represent code blocks , You don't need braces {} .

The number of indented spaces is variable , But the statements of the same code block must contain the same number of indented spaces .

Indents are inconsistent , Can cause errors :IndentationError: unindent does not match any outer indentation level

6. Multi line statement

Python It's usually a sentence written one line at a time , But if the sentence is long , We can use backslash ** To implement multiline statements , for example :

total = item_one + \
item_two + \
item_three

stay [], {}, or () Multiple lines in , No need to use backslash ****, for example :

total = ['item_one', 'item_two', 'item_three',
'item_four', 'item_five']

7. Numbers (Number) type

python There are four types of middle numbers : Integers 、 Boolean type 、 Floating point and complex number .

  • int ( Integers ), Such as 1, There is only one integer type int, Expressed as a long integer , No, python2 Medium Long.
  • bool ( Boolean ), Such as True.
  • float ( Floating point numbers ), Such as 1.23、3E-2
  • complex ( The plural ), Such as 1 + 2j、 1.1 + 2.2j

8. character string (String)

  • python The use of single and double quotation marks in is exactly the same .
  • Use three quotes (’’’ or “”") You can specify a multiline string .
  • Escape character \
  • Backslash can be used to escape , Use r You can keep the backslash from escaping .. Such as r"this is a line with \n" be \n Will be displayed , It's not a new line .
  • Concatenate strings literally , Such as "this " "is " "string" Will be automatically converted to this is string.
  • Strings can use + Operator join together , use * Operator repetition .
  • Python There are two ways to index strings in , From left to right 0 Start , From right to left -1 Start .
  • Python String in cannot be changed .
  • Python No separate character type , One character is the length of 1 String .
  • The syntax format of string truncation is as follows : Variable [ Header subscript : Tail subscript : step ]
#!/usr/bin/python3
str='123456789'
print(str) # Output string 
print(str[0:-1]) # Output all characters from the first to the last 
print(str[0]) # The first character of the output string 
print(str[2:5]) # Output characters from the third to the fifth 
print(str[2:]) # Output all characters starting from the third 
print(str[1:5:2]) # Output every other character from the second to the fifth ( In steps of 2)
print(str * 2) # Output string twice 
print(str + ' Hello ') # Connection string 
print('------------------------------')
print('hello\nrunoob') # Use backslash (\)+n Escapes special characters 
print(r'hello\nrunoob') # Add a... Before the string r, Represents the original string , There will be no escape 

9. Waiting for user input

The following program will wait for user input after pressing enter :

#!/usr/bin/python3
input("\n\n Press down enter Key to exit .")

10. Show multiple statements on the same line

Python You can use multiple statements on the same line , Use semicolons... Between statements ; Division , Here is a simple example :

#!/usr/bin/python3
import sys; x = 'runoob'; sys.stdout.write(x + '\n')

11. print Output

print The default output is line feed , If you want to implement no line wrapping, you need to add... At the end of the variable end=""

#!/usr/bin/python3
x="a"
y="b"
# Line feed output 
print( x )
print( y )
print('---------')
# Don't wrap output 
print( x, end=" " )
print( y, end=" " )
print()

12. Module import import And from…import

stay python use import perhaps from…import To import the corresponding module .

The whole module (somemodule) Import , The format is : import somemodule

Import a function from a module , The format is : from somemodule import somefunction

Import multiple functions from a module , The format is : from somemodule import firstfunc, secondfunc, thirdfunc

Import all functions in a module into , The format is : from somemodule import *

# Import sys modular 
import sys
print('================Python import mode==========================')
print (' The command line arguments are :')
for i in sys.argv:
print (i)
print ('\n python Path is ',sys.path)
# Import sys Modular argv、path member 
from sys import argv,path # Import specific members 
print('================python from import===================================')
print('path:',path) # Because it has been imported path member , So there is no need to add sys.path

13. Command line arguments

$ python test.py arg1 arg2 arg3

(1)Python It can also be used in sys Of sys.argv To get command line arguments :

  • sys.argv Is a list of command line arguments .
  • len(sys.argv) Calculate the number of command line parameters .

notes :sys.argv[0] Represents the script name .

#!/usr/bin/python3
import sys
print (' The number of parameters is :', len(sys.argv), ' Parameters .')
print (' parameter list :', str(sys.argv))
print (' Script name :', str(sys.argv[0]))

Execution results :

$ python3 test.py arg1 arg2 arg3
The number of parameters is : 4 Parameters .
parameter list : ['test.py', 'arg1', 'arg2', 'arg3']
Script name : test.py

(2)getopt modular

getopt A module is a module that deals specifically with command-line arguments , Used to get command line options and parameters , That is to say sys.argv. Command line options make program parameters more flexible . Support short option mode - And long option mode .

This module provides two methods and an exception handling to parse command line parameters .

getopt.getopt Method

getopt.getopt Method is used to parse the command line argument list , The syntax is as follows :

getopt.getopt(args, options[, long_options])

Method parameter description :

  • args: List of command line arguments to parse .
  • options: Define... In the form of a string ,options The colon after : Indicates that the option must have additional parameters , Without a colon, it means that the option has no additional parameters .
  • long_options: Define... In the form of a list ,long_options The later equal sign = Indicates if the option is set , There must be additional parameters , Otherwise, there will be no additional parameters .

The return value of this method consists of two elements : The first is (option, value) A list of tuples . The second is the parameter list , Including those not - or Parameters of .

Let's define a site() function , Then enter the site name from the command line name And website url, You can use abbreviations n and u:

Two 、 Basic data type

Python Variables in do not need to be declared . Each variable must be assigned a value before use , The variable will not be created until it is assigned a value .

stay Python in , Variable is variable , It has no type , What we say " type " Is the type of object in memory that the variable refers to .

Equal sign (=) Used to assign values to variables .

Equal sign (=) To the left of the operator is a variable name , Equal sign (=) To the right of the operator is the value stored in the variable .

1. Multiple variable assignments

Python Allows you to assign values to multiple variables at the same time . for example :

a = b = c = 1

The above instance , Create an integer object , The value is 1, Assign from back to front , Three variables are given the same value .

You can also specify multiple variables for multiple objects . for example :

a, b, c = 1, 2, "runoob"

The above instance , Two integer objects 1 and 2 Assigned to variables a and b, String object “runoob” Assign to a variable c.

2. Standard data type

Python3 There are six standard data types in :

  • Number( Numbers )
  • String( character string )
  • List( list )
  • Tuple( Tuples )
  • Set( aggregate )
  • Dictionary( Dictionaries )

Python3 Of the six standard data types :

  • ** Immutable data (3 individual ):**Number( Numbers )、String( character string )、Tuple( Tuples );
  • ** Variable data (3 individual ):**List( list )、Dictionary( Dictionaries )、Set( aggregate ).
  • string、list and tuple All belong to sequence( Sequence ).

3. Number( Numbers )

Python3 Support int、float、bool、complex( The plural ).

stay Python 3 in , There is only one integer type int, Expressed as a long integer , No, python2 Medium Long.

Like most languages , The assignment and calculation of numerical types are very intuitive .

Built in type() Function can be used to query the object type of variable .

>>> a, b, c, d = 20, 5.5, True, 4+3j
>>> print(type(a), type(b), type(c), type(d))
<class 'int'> <class 'float'> <class 'bool'> <class 'complex'>

It can also be used isinstance To judge :

>>> a = 111
>>> isinstance(a, int)
True
>>>

isinstance and type The difference is that :

  • type() A subclass is not considered a superclass type .
  • isinstance() Think of a subclass as a superclass type .

** Be careful :*Python3 in ,bool yes int Subclasses of ,True and False Can be added to numbers , True1、False0 Returns the True, But it can go through is To judge the type

When you specify a value ,Number The object will be created :

var1 = 1
var2 = 10

You can also use the del Statement to delete some object references .

del var
del var_a, var_b

Numerical operation

\>>> 5 + 4 # Add 
9
\>>> 4.3 - 2 # Subtraction 
2.3
\>>> 3 * 7 # Multiplication 
21
\>>> 2 / 4 # division , Get a floating point number 
0.5
\>>> 2 // 4 # division , Get an integer 
0
\>>> 17 % 3 # Remainder 
2
\>>> 2 ** 5 # chengfang (2 Of 5 Power )
32

Be careful :

  • 1、Python Multiple variables can be assigned at the same time , Such as a, b = 1, 2.
  • 2、 A variable can be assigned to different types of objects .
  • 3、 The division of a number consists of two operators :/ Returns a floating point number ,// Returns an integer .
  • 4、 In mixed calculation ,Python Will convert integer to floating point .

4.String( character string )

Python Use single quotes for strings in Or double quotes " Cover up , Use the backslash at the same time ** Escapes special characters .

The syntax format of string truncation is as follows :

 Variable [ Header subscript : Tail subscript ]

Index value to 0 For starting value ,-1 To start at the end .

[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-4nc2z5Xy-1645023022787)(https://gitee.com/songjie001/typora_pictures/raw/master/123456-20200923-1.svg)]

plus + Is the concatenator of a string , asterisk * Means to copy the current string , The combined number is the number of copies

Python Use backslash ** Escapes special characters , If you don't want the backslash to escape , You can add a... Before the string r, Represents the original string :

>>> print('Ru\noob')
Ru
oob
>>> print(r'Ru\noob')
Ru\noob
>>>

in addition , The backslash () It can be used as a continuation , Indicates that the next line is a continuation of the previous line . You can also use “”"…""" perhaps ‘’’…’’’ Across many lines .

Be careful ,Python No separate character type , One character is the length of 1 String .

And C The difference between strings is ,Python String cannot be changed . Assign a value to an index location , such as word[0] = 'm’ Can cause errors .

Be careful :

  • 1、 Backslash can be used to escape , Use r You can keep the backslash from escaping .
  • 2、 String can be used + Operators join together , use * Operator repetition .
  • 3、Python There are two ways to index strings in , From left to right 0 Start , From right to left -1 Start .
  • 4、Python String in cannot be changed .

5.List( list )

List( list ) yes Python The most frequently used data type in .

List can complete the data structure implementation of most collection classes . The types of elements in a list can vary , It supports Numbers , Strings can even contain lists ( The so-called nested ).

The list is written in square brackets [] Between 、 Comma separated list of elements .

Just like a string , The list can also be indexed and intercepted , After the list is truncated, a new list containing the required elements is returned .

The syntax format of list truncation is as follows :

 Variable [ Header subscript : Tail subscript ]

Index value to 0 For starting value ,-1 To start at the end .

plus + Is the list join operator , asterisk ***** Is a repeat operation . The following example :

#!/usr/bin/python3
list = [ 'abcd', 786 , 2.23, 'runoob', 70.2 ]
tinylist = [123, 'runoob']
print (list) # Output complete list 
print (list[0]) # The first element of the output list 
print (list[1:3]) # Output from the second to the third element 
print (list[2:]) # Output all elements starting with the third element 
print (tinylist * 2) # Output the list twice 
print (list + tinylist) # Connection list 

And Python The difference between strings is , The elements in the list can be changed :

>>> a = [1, 2, 3, 4, 5, 6]
>>> a[0] = 9
>>> a[2:5] = [13, 14, 15]
>>> a
[9, 2, 13, 14, 15, 6]
>>> a[2:5] = [] # Set the corresponding element value to []
>>> a
[9, 2, 6]

List Built in there are many ways , for example append()、pop() wait , This will be discussed later .

Be careful :

  • 1、List Write between square brackets , The elements are separated by commas .
  • 2、 Just like a string ,list Can be indexed and sliced .
  • 3、List have access to + Operators are spliced .
  • 4、List The elements in can be changed .

Python List interception can receive the third parameter , The parameter function is the step size of interception , The following examples are in the index 1 To the index 4 And set the step size to 2( One place apart ) To intercept a string :

If the third parameter is negative, it means reverse reading , The following example is used to flip a string :

def reverseWords(input):
# String separator with spaces , Separate words into lists 
inputWords = input.split(" ")
# Flip strings 
# What if list list = [1,2,3,4], 
# list[0]=1, list[1]=2 , and -1 Represents the last element list[-1]=4 ( And list[3]=4 equally )
# inputWords[-1::-1] There are three parameters 
# The first parameter -1 Represents the last element 
# The second parameter is empty , Means to move to the end of the list 
# The third parameter is the step ,-1 It means reverse 
inputWords=inputWords[-1::-1]
# Recombine strings 
output = ' '.join(inputWords)
return output
if __name__ == "__main__":
input = 'I like runoob'
rw = reverseWords(input)
print(rw)

6.Tuple( Tuples )

Tuples (tuple) Like a list , The difference is The element of a tuple cannot be modified . Tuples are written in parentheses () in , The elements are separated by commas .

The element types in tuples can also be different :

#!/usr/bin/python3
tuple = ( 'abcd', 786 , 2.23, 'runoob', 70.2 )
tinytuple = (123, 'runoob')
print (tuple) # Output full tuples 
print (tuple[0]) # The first element of the output tuple 
print (tuple[1:3]) # The output starts with the second element and goes to the third element 
print (tuple[2:]) # Output all elements starting with the third element 
print (tinytuple * 2) # Output tuples twice 
print (tuple + tinytuple) # Join tuples 

Tuples are similar to strings , Can be indexed and subscript indexed from 0 Start ,-1 For the position starting from the end . You can also intercept ( Look at it , No more details here ).

Actually , You can think of a string as a special tuple .

although tuple The element of cannot be changed , But it can contain mutable objects , such as list list .

Tectonic inclusion 0 Or 1 Tuples of elements are special , So there are some extra grammatical rules :

tup1 = () # An empty tuple 
tup2 = (20,) # An element , Comma needs to be added after element 

string、list and tuple All belong to sequence( Sequence ).

Be careful :

  • 1、 Same as string , The element of a tuple cannot be modified .
  • 2、 Tuples can also be indexed and sliced , The method is the same .
  • 3、 Notice that the construction contains 0 or 1 Special syntax rules for tuples of elements .
  • 4、 Tuples can also be used + Operators are spliced .

7. Set( aggregate )

aggregate (set) By one or more ** Come in all shapes ( Do not include duplicate elements )** The size of the whole composition of , The things or objects that make up a set are called elements or members .

The basic function is to test membership and remove duplicate elements .

You can use braces { } perhaps set() Function to create a collection , Be careful : To create an empty collection, you must use the set() instead of { }, because { } Is used to create an empty dictionary .

Create format :

parame = {value01,value02,...}
perhaps
set(value)
#!/usr/bin/python3
sites = {
'Google', 'Taobao', 'Runoob', 'Facebook', 'Zhihu', 'Baidu'}
print(sites) # Output set , Duplicate elements are automatically removed 
# Members of the test 
if 'Runoob' in sites :
print('Runoob In the assembly ')
else :
print('Runoob Not in the assembly ')
# set You can do set operations 
a = set('abracadabra')
b = set('alacazam')
print(a)
print(a - b) # a and b The difference between the set 
print(a | b) # a and b Union 
print(a & b) # a and b Intersection 
print(a ^ b) # a and b Elements that do not exist at the same time in 

8.Dictionary( Dictionaries )

Dictionaries (dictionary) yes Python Another very useful built-in data type in .

A list is an ordered collection of objects , The dictionary is disorder Object collection for . The difference between the two is : The elements in the dictionary are Access by key Of , Instead of accessing by offset .

Dictionary is another variable container model , And can store any type of object .

Each key value of the dictionary key=>value Yes, with a colon : Division , Use commas... Between each pair (,) Division , The whole dictionary is enclosed in curly brackets {} in , The format is as follows :

d = {
key1 : value1, key2 : value2, key3 : value3 }

key (key) Characteristics of :

1) Immutable type must be used , Such as a string 、 Array 、 Tuples ;

2) In the same dictionary , key (key) Must be unique , When creating, if the same key is assigned twice , The latter value will be remembered .

#!/usr/bin/python3
dict = {
}
dict['one'] = "1 - Novice tutorial "
dict[2] = "2 - Rookie tools "
tinydict = {
'name': 'runoob','code':1, 'site': 'www.runoob.com'}
print (dict['one']) # The output key is 'one' Value 
print (dict[2]) # The output key is 2 Value 
print (tinydict) # Output complete dictionary 
print (tinydict.keys()) # Output all keys 
print (tinydict.values()) # Output all values 

Constructors dict() You can build a dictionary directly from the sequence of key value pairs as follows :

>>> dict([('Runoob', 1), ('Google', 2), ('Taobao', 3)])
{
'Runoob': 1, 'Google': 2, 'Taobao': 3}
>>> {
x: x**2 for x in (2, 4, 6)}
{
2: 4, 4: 16, 6: 36}
>>> dict(Runoob=1, Google=2, Taobao=3)
{
'Runoob': 1, 'Google': 2, 'Taobao': 3}
>>>

in addition , Dictionary types also have some built-in functions , for example clear()、keys()、values() etc. .

Be careful :

  • 1、 A dictionary is a mapping type , Its element is a key value pair .
  • 2、 Dictionary keywords must be immutable , And can't repeat .
  • 3、 Create an empty dictionary to use { }.

Revise the dictionary

The way to add new content to the dictionary is to add new keys / It's worth it , Modify or delete existing keys / The value pairs are as follows :

#!/usr/bin/python3
dict = {
'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
dict['Age'] = 8 # to update Age
dict['School'] = " Novice tutorial " # Add information 
print ("dict['Age']: ", dict['Age'])
print ("dict['School']: ", dict['School'])

Delete dictionary elements del

Can delete a single element can also empty the dictionary , Emptying takes only one operation .

Show delete a dictionary with del command , The following example :

#!/usr/bin/python3
dict = {
'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
del dict['Name'] # Delete key 'Name'
dict.clear() # Empty dictionary 
del dict # Delete Dictionary 
print ("dict['Age']: ", dict['Age'])
print ("dict['School']: ", dict['School'])

Dictionary built-in functions and methods

dict.keys() # Get all the keys 
dict.values() # Get all the values 
dict.clear() # Empty dictionary 
len(dict) # Count the number of dictionary elements , That's the total number of bonds 
str(dict) # Output Dictionary , A printable string represents .
type(variable) # Returns the type of variable entered , If the variable is a dictionary, return the dictionary type .
radiansdict.get(key, default=None) # Returns the value of the specified key , If the key is not in the dictionary, return default Set the default value of 
dict.pop(key[,default]) # Delete dictionary given key key The corresponding value , The return value is the deleted value .key Value must be given . otherwise , return default value .
key in dict # If the key is in the dictionary dict Back in true, Otherwise return to false
dict.copy() # Returns a shallow copy of a dictionary 
dict.items() # Returns a view object as a list 
radiansdict.keys() # Returns a view object 

9.Python Data type conversion

occasionally , We need to transform the built-in types of data , Conversion of data types , You just need to use the data type as the function name .

The following built-in functions can perform conversion between data types . These functions return a new object , Represents the value of the transformation .

function describe [int(x ,base]) take x Convert to an integer float(x) take x Converts to a floating point number [complex(real ,imag]) Create a complex number 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 (string、list and tuple All belong to sequence( Sequence ).)list(s) The sequence of s Convert to a list set(s) Convert to variable set dict(d) Create a dictionary .d Must be a (key, value) Tuple sequence .frozenset(s) Convert to immutable set chr(x) Converts an integer to a character ord(x) Converts a character to its integer value hex(x) Convert an integer to a hexadecimal string oct(x) Converts an integer to an octal string

3、 ... and 、 Operator

Four 、 Under controlled conditions 、 loop 、 iteration

1. if sentence

if condition_1:
statement_block_1
elif condition_2:
statement_block_2
else:
statement_block_3
  • If “condition_1” by True Will perform “statement_block_1” Block statement
  • If “condition_1” by False, Will judge “condition_2”
  • If "condition_2" by True Will perform “statement_block_2” Block statement
  • If “condition_2” by False, Will perform "statement_block_3" Block statement

Python of use elif Instead of else if, therefore if The keyword of the statement is :if – elif – else.

Be careful :

  • 1、 Use a colon after each condition :, Indicates the statement block to be executed after the condition is met .
  • 2、 Use indentation to divide statement blocks , Statements with the same indentation number form a statement block together .
  • 3、 stay Python in No, switch – case sentence .

if nesting

In nesting if In the sentence , You can put if…elif…else The structure is placed in another if…elif…else In structure .

if expression 1:
sentence
if expression 2:
sentence
elif expression 3:
sentence
else:
sentence
elif expression 4:
sentence
else:
sentence

2.while Loop statement

While loop

while Judge the condition (condition):
Execute statement (statements)……

Also notice colons and indents . in addition , stay Python There is no do…while loop .

while Recycling else sentence

If while The following conditional statement is false when , execute else Statement block .

The syntax is as follows :

while <expr>:
<statement(s)>
else:
<additional_statement(s)>

expr The conditional statement is true execute statement(s) Sentence block , If false, execute additional_statement(s).

Simple statement group

similar if Sentence syntax , If your while There is only one statement in the body of the loop , You can match the statement with while In the same line , As shown below :

#!/usr/bin/python
flag = 1
while (flag): print (' Welcome to the rookie tutorial !')
print ("Good bye!")

3. for loop

Python for Loops can traverse any iteratable object , Like a list or a string .

for The general format of the loop is as follows :

for <variable> in <sequence>:
<statements>
else:
<statements>

following for The example uses break sentence ,break Statement is used to jump out of the current loop :

#!/usr/bin/python3
sites = ["Baidu", "Google","Runoob","Taobao"]
for site in sites:
if site == "Runoob":
print(" Novice tutorial !")
break
print(" Loop data " + site)
else:
print(" There's no circular data !")
print(" Complete the cycle !")

range() function

If you need to traverse a sequence of numbers , You can use built-in range() function . It generates a sequence , for example :

for i in range(5):
print(i)
# have access to range Specify the value of the interval :
for i in range(5,9) :
print(i)
# You can make range Start with a specified number and specify a different increment ( It can even be negative , Sometimes it's also called ' step '):
for i in range(0, 10, 3) :
print(i)

Can combine range() and len() Function to traverse the index of a sequence , As shown below :

>>>a = ['Google', 'Baidu', 'Runoob', 'Taobao', 'QQ']
>>> for i in range(len(a)):
... print(i, a[i])
...
0 Google
1 Baidu
2 Runoob
3 Taobao
4 QQ

break And continue:

break Sentences can jump out of for and while Circulatory body of . If you for or while To terminate in a cycle , Any corresponding cycle else Block will not execute .

continue Statements are used to tell Python Skip the remaining statements in the current loop block , Then proceed to the next cycle .

pass sentence :

Python pass It's an empty statement , To maintain the integrity of the program structure .

pass Not doing anything , Generally used as occupation statement , The following example :

#!/usr/bin/python3
for letter in 'Runoob':
if letter == 'o':
pass
print (' perform pass block ')
print (' The current letter :', letter)
print ("Good bye!")

4. iterator

Iteration is Python One of the most powerful features , Is a way to access collection elements .

An iterator is an object that remembers the traversal location .

The iterator object is accessed from the first element of the collection , Until all elements are accessed . Iterators can only move forward and not backward .

There are two basic ways to iterator :iter() and next().

character string , List or tuple objects can be used to create iterators :

>>> list=[1,2,3,4]
>>> it = iter(list) # Create iterator object 
>>> print (next(it)) # The next element of the output iterator 
1
>>> print (next(it))
2
>>>

Iterator objects can use regular for Statement to traverse :

#!/usr/bin/python3
list=[1,2,3,4]
it = iter(list) # Create iterator object 
for x in it:
print (x, end=" ")

You can also use next() function :

#!/usr/bin/python3
import sys # introduce sys modular 
list=[1,2,3,4]
it = iter(list) # Create iterator object 
while True:
try:
print (next(it))
except StopIteration:
sys.exit()

Create an iterator

Using a class as an iterator requires implementing two methods in the class iter() And next() .

If you already know object-oriented programming , You know that every class has a constructor ,Python The constructor for is init(), It will execute when the object is initialized .

iter() Method returns a special iterator object , This iterator object implements next() Method and pass StopIteration The exception marks the completion of the iteration .

next() Method (Python 2 Is in the next()) The next iterator object is returned .

Create an iterator that returns a number , The initial value is 1, Gradually increasing 1;

StopIteration Exceptions are used to identify the completion of an iteration , To prevent infinite loops , stay next() Method, we can set to trigger after completing the specified number of cycles StopIteration Exception to end the iteration .

stay 20 Stop execution after iteration :

class MyNumbers:
def __iter__(self):
self.a = 1
return self
def __next__(self):
if self.a <= 20:
x = self.a
self.a += 1
return x
else:
raise StopIteration
myclass = MyNumbers()
myiter = iter(myclass)
for x in myiter:
print(x)

generator

stay Python in , Used yield The function of the is called the generator (generator).

Different from ordinary functions , A generator is a function that returns an iterator , Can only be used for iterative operations , It's easier to understand that a generator is an iterator .

During the call generator run , Every encounter yield Function will pause and save all current running information , return yield Value , And next time next() Method to continue from the current location .

Call a generator function , Returns an iterator object .

The following example uses yield Realization of Fibonacci series :

#!/usr/bin/python3
import sys
def fibonacci(n): # Generator function - Fibonacci 
a, b, counter = 0, 1, 0
while True:
if (counter > n):
return
yield a
a, b = b, a + b
counter += 1
f = fibonacci(10) # f It's an iterator , Build returned by generator 
while True:
try:
print (next(f), end=" ")
except StopIteration:
sys.exit()

5、 ... and 、 function

Functions are organized , Reusable , To achieve oneness , Or code snippets associated with functions .

Function can improve the modularity of application , And code reuse . You already know Python Many built-in functions are provided , such as print(). But you can also create your own functions , This is called a user-defined function .


1. Define a function

You can define a function that you want to function , Here are the simple rules :

  • Function code block to def Key words start with , Followed by function identifier name and parentheses ().
  • Any arguments and arguments passed in must be placed between parentheses , Parentheses can be used to define parameters .
  • The first line of the function optionally uses the document string — Used to store function descriptions .
  • The function content is colon : start , And indent .
  • return [ expression ] End function , Optionally return a value to the caller , Without expression return It's equivalent to returning to None.

grammar

Python Define function use def keyword , The general format is as follows :

def Function name ( parameter list ):
The body of the function

By default , Parameter values and parameter names match in the order defined in the function declaration .

2. Function call

Define a function : Give the function a name , Specifies the parameters contained in the function , And code block structure .

After the basic structure of this function is completed , You can do this through another function call , You can also go straight from Python Command prompt execution .

The following example calls printme() function :

#!/usr/bin/python3
# Defined function 
def printme( str ):
# Print any incoming strings 
print (str)
return
# Call function 
printme(" I'm going to call user defined functions !")
printme(" Call the same function again ")

3. Parameter passing

stay python in , Type belongs to object , Variables have no type Of :

a=[1,2,3]
a="Runoob"

In the above code ,[1,2,3] yes List type ,"Runoob" yes String type , Variables a There is no type , She's just a reference to an object ( A pointer ), It can point to List Type object , It can also point to String Type object .

Changeable (mutable) And cannot be changed (immutable) object

stay python in ,strings, tuples, and numbers Is an object that cannot be changed , and list,dict And so on are modifiable objects .

  • ** Immutable type :** Variable assignment a=5 After the assignment a=10, This is actually a new generation of int The value object 10, let a Pointing to it , and 5 To be discarded , Not change a Value , It's equivalent to a new generation of a.
  • ** Variable type :** Variable assignment la=[1,2,3,4] After the assignment la[2]=5 Will be list la The third element value of changes , In itself la Didn't move , Only part of its internal value has been modified .

python Parameter passing of function :

  • ** Immutable type :** similar C++ Value transfer of , Such as integers 、 character string 、 Tuples . Such as fun(a), It's just a Value , No impact a Object itself . If in fun(a) Internal modification a Value , Is a newly generated a The object of .
  • ** Variable type :** similar C++ By reference , Such as list , Dictionaries . Such as fun(la), Will be la Really pass it on , After modification fun External la It will also be affected

python Everything in is the object , Strictly speaking, we can't say value passing or reference passing , We should talk about immutable objects and mutable objects .

python Pass immutable object instance

adopt id() Function to see the memory address change :

def change(a):
print(id(a)) # It's pointing to the same object 
a=10
print(id(a)) # A new object ( Not affected in the main program )
a=1
print(id(a))
change(a)

You can see that before and after calling the function , Formal parameter and argument point to the same object ( object id identical ), After modifying the formal parameters inside the function , Formal parameters point to different id.

Pass variable object instance

The variable object modifies the parameters in the function , So in the function that calls this function , The original parameters have also been changed . for example :

#!/usr/bin/python3
# Write function description 
def changeme( mylist ):
" Modify the incoming list "
mylist.append([1,2,3,4])
print (" Value in function : ", mylist)
return
# call changeme function 
mylist = [10,20,30]
changeme( mylist )
print (" Value outside the function : ", mylist) # Same as function internal value , Change 

4. Parameters

Here are the formal parameter types that can be used when calling a function :

  • Required parameters
  • Key parameters
  • Default parameters
  • Indefinite length parameter

Required parameters

The required parameters must be passed into the function in the correct order . The number of calls must be the same as when they were declared .

call printme() function , You have to pass in a parameter , Otherwise, there will be grammatical errors :

#!/usr/bin/python3
# Write function description 
def printme( str ):
" Print any incoming strings "
print (str)
return
# call printme function , Without parameters, an error will be reported 
printme()

Key parameters

Keyword parameters are closely related to function calls , Function calls use key arguments to determine the value of the arguments passed in .

Using keyword parameters allows the order of parameters when a function is called to be different from when it is declared , because Python The interpreter can match parameter values with parameter names .

The following example is in the function printme() Call with parameter name :

#!/usr/bin/python3
# Write function description 
def printme( str ):
" Print any incoming strings "
print (str)
return
# call printme function 
printme( str = " Novice tutorial ")

Default parameters

When you call a function , If no parameters are passed , Then the default parameters . In the following example, if no age Parameters , The default value is used :

#!/usr/bin/python3
# Write function description 
def printinfo( name, age = 35 ):
" Print any incoming strings "
print (" name : ", name)
print (" Age : ", age)
return
# call printinfo function 
printinfo( age=50, name="runoob" )
print ("------------------------")
printinfo( name="runoob" )

Indefinite length parameter

You may need a function that can handle more arguments than it was originally declared . These parameters are called indefinite length parameters , And above 2 The parameters are different , Declaration will not be named . The basic grammar is as follows :

def functionname([formal_args,] *var_args_tuple ):
" function _ docstring "
function_suite
return [expression]

(1) added asterisk * The parameters of will be in tuples (tuple) The form of import , Store all unnamed variable parameters .

#!/usr/bin/python3
# Write function description 
def printinfo( arg1, *vartuple ):
" Print any incoming parameters "
print (" Output : ")
print (arg1)
print (vartuple)
# call printinfo function 
printinfo( 70, 60, 50 )

If no parameters are specified in the function call , It's just an empty tuple . We can also avoid passing unnamed variables to functions . The following example :

#!/usr/bin/python3
# Write function description 
def printinfo( arg1, *vartuple ):
" Print any incoming parameters "
print (" Output : ")
print (arg1)
for var in vartuple:
print (var)
return
# call printinfo function 
printinfo( 10 )
printinfo( 70, 60, 50 )

(2) added * Two asterisks * Will be imported as a dictionary .

#!/usr/bin/python3
# Write function description 
def printinfo( arg1, **vardict ):
" Print any incoming parameters "
print (" Output : ")
print (arg1)
print (vardict)
# call printinfo function 
printinfo(1, a=2,b=3)

When you declare a function , Asterisk in parameter ***** Can appear alone ; If the asterisk appears alone ***** The parameter after must be passed in with the keyword .

>>> def f(a,b,*,c):
... return a+b+c
...
>>> f(1,2,3) # Report errors 
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: f() takes 2 positional arguments but 3 were given
>>> f(1,2,c=3) # normal 
6
>>>

5. Anonymous functions

python Use lambda To create anonymous functions .

So called anonymity , It means to stop using def Statement defines a function in this standard form .

  • lambda It's just an expression , Function volume ratio def Simple a lot .
  • lambda The subject of is an expression , Not a block of code . Only in lambda Expressions encapsulate limited logic .
  • lambda Function has its own namespace , And can't access parameters outside their parameter list or in the global namespace .
  • although lambda The function looks like it can only write one line , But it's not the same as C or C++ Inline function , The purpose of the latter is not to occupy stack memory when calling small functions so as to increase the running efficiency .

grammar

lambda The syntax of a function contains only one statement , as follows :

lambda [arg1 [,arg2,.....argn]]:expression
#!/usr/bin/python3
# Write function description 
sum = lambda arg1, arg2: arg1 + arg2
# call sum function 
print (" The sum is : ", sum( 10, 20 ))
print (" The sum is : ", sum( 20, 20 ))

6.return sentence

return [ expression ] Statement is used to exit a function , Optionally return an expression... To the caller . Without parameter value return Statement returns None. None of the previous examples demonstrated how to return a value , The following example demonstrates return Usage of sentences :

#!/usr/bin/python3
# Write function description 
def sum( arg1, arg2 ):
# return 2 The sum of parameters ."
total = arg1 + arg2
print (" Within the function : ", total)
return total
# call sum function 
total = sum( 10, 20 )
print (" Out of function : ", total)

7. Force position parameters

Python3.8 Added a function parameter Syntax / Used to indicate that the function parameter must use the specified positional parameter , Cannot use the form of keyword parameter .

In the following example , Shape parameter a and b You must use the specified positional parameter ,c or d It can be a location parameter or a keyword parameter , and e and f Keyword parameter required :

def f(a, b, /, c, d, *, e, f):
print(a, b, c, d, e, f)

The following usage is correct :

f(10, 20, 30, d=40, e=50, f=60)

The following usage method will make mistakes :

f(10, b=20, c=30, d=40, e=50, f=60) # b Cannot use the form of keyword parameter 
f(10, 20, 30, 40, 50, f=60) # e Must be in the form of a keyword parameter 

6、 ... and 、 data structure

1. list

Python The list in is variable , This is the most important feature that distinguishes it from strings and tuples , In a word, it is : The list can be modified , And strings and tuples cannot .

Common ways of listing :

Here are Python Methods in the list :

Method describe list.append(x) Add an element to the end of the list , amount to a[len(a):] = [x].list.extend(L) Expand the list by adding all the elements of the specified list , amount to a[len(a):] = L.list.insert(i, x) Inserts an element at the specified location . The first parameter is the index of the element to be inserted in front of it , for example a.insert(0, x) Will be inserted before the entire list , and a.insert(len(a), x) amount to a.append(x) .list.remove(x) Delete the value in the list as x The first element of . If there is no such element , It will return an error .list.pop([i]) Remove the element from the specified position in the list , And return it . If no index is specified ,a.pop() Return to the last element . The element is then removed from the list .( In the method i Square brackets on both sides indicate that this parameter is optional , Instead of asking you to enter a square bracket , You will often be in Python This tag is encountered in the library reference manual .)list.clear() Remove all items from the list , be equal to del a[:].list.index(x) The first value in the return list is x The index of the element . If there is no matching element, an error is returned .list.count(x) return x The number of times in the list .list.sort() Sort the elements in the list .list.reverse() The elements in the inverted list .list.copy() Returns a shallow copy of the list , be equal to a[:].

The following example demonstrates most of the methods of listing :

>>> a = [66.25, 333, 333, 1, 1234.5]
>>> print(a.count(333), a.count(66.25), a.count('x'))
2 1 0
>>> a.insert(2, -1)
>>> a.append(333)
>>> a
[66.25, 333, -1, 333, 1, 1234.5, 333]
>>> a.index(333)
1
>>> a.remove(333)
>>> a
[66.25, -1, 333, 1, 1234.5, 333]
>>> a.reverse()
>>> a
[333, 1234.5, 1, 333, -1, 66.25]
>>> a.sort()
>>> a
[-1, 1, 66.25, 333, 333, 1234.5]

Use the list as a stack

The list method makes it easy to use the list as a stack , Stack as a specific data structure , The first element to enter is the last one to be released ( Last in, first out ). use append() Method can add an element to the top of the stack . With no index specified pop() Method can release an element from the top of the stack . for example :

>>> stack = [3, 4, 5]
>>> stack.append(6)
>>> stack.append(7)
>>> stack
[3, 4, 5, 6, 7]
>>> stack.pop()
7
>>> stack
[3, 4, 5, 6]
>>> stack.pop()
6
>>> stack.pop()
5
>>> stack
[3, 4]

Use the list as a queue

You can also use the list as a queue , Just the first element in the queue , The first to take it out ; But it's not efficient to use lists for such purposes . It's faster to add or pop up elements at the end of the list , However, it's not fast to insert in the list or pop it out of the head ( Because all the other elements have to move one by one ).

>>> from collections import deque
>>> queue = deque(["Eric", "John", "Michael"])
>>> queue.append("Terry") # Terry arrives
>>> queue.append("Graham") # Graham arrives
>>> queue.popleft() # The first to arrive now leaves
'Eric'
>>> queue.popleft() # The second to arrive now leaves
'John'
>>> queue # Remaining queue in order of arrival
deque(['Michael', 'Terry', 'Graham'])

List derivation

List derivation provides a simple way to create a list from a sequence . Usually applications Apply some operations to each element of a sequence , Use the result as an element to generate a new list , Or create subsequences according to certain criteria .

Every list derivation is in for Followed by an expression , Then there are zero to many for or if Clause . The return result is based on the expression from the following for and if The list generated in the context . If you want the expression to derive a tuple , You have to use brackets .

Here we multiply each value in the list by three , Get a new list :

>>> vec = [2, 4, 6]
>>> [3*x for x in vec]
[6, 12, 18]

Now let's play a little trick :

>>> [[x, x**2] for x in vec]
[[2, 4], [4, 16], [6, 36]]

Here we call a method one by one for each element in the sequence :

>>> freshfruit = [' banana', ' loganberry ', 'passion fruit ']
>>> [weapon.strip() for weapon in freshfruit]
['banana', 'loganberry', 'passion fruit']

We It can be used if Clause as filter

>>> [3*x for x in vec if x > 3]
[12, 18]
>>> [3*x for x in vec if x < 2]
[]

Here are some demonstrations of loops and other techniques :

>>> vec1 = [2, 4, 6]
>>> vec2 = [4, 3, -9]
>>> [x*y for x in vec1 for y in vec2]
[8, 6, -18, 16, 12, -36, 24, 18, -54]
>>> [x+y for x in vec1 for y in vec2]
[6, 5, -7, 8, 7, -5, 10, 9, -3]
>>> [vec1[i]*vec2[i] for i in range(len(vec1))]
[8, 12, -54]

Nested list parsing

Python Lists can also be nested .

The following example shows 3X4 Of Matrix list

>>> matrix = [
... [1, 2, 3, 4],
... [5, 6, 7, 8],
... [9, 10, 11, 12],
... ]

The following examples will 3X4 The matrix list of is converted to 4X3 list :( Matrix transposition )

>>> [[row[i] for row in matrix] for i in range(4)]
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

It can also be implemented in the following ways :

>>> transposed = []
>>> for i in range(4):
... transposed.append([row[i] for row in matrix])
...
>>> transposed
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

del sentence

Use del Statement can delete an element from a list by index rather than value . This is with the use of pop() Return a value different from . It can be used del Statement to remove a cut from the list , Or empty the entire list ( The method we introduced earlier is to assign an empty list to the cut ). for example :

>>> a = [-1, 1, 66.25, 333, 333, 1234.5]
>>> del a[0]
>>> a
[1, 66.25, 333, 333, 1234.5]
>>> del a[2:4]
>>> a
[1, 66.25, 1234.5]
>>> del a[:]
>>> a

It can also be used. del Delete entity variable :

>>> del a

2. Tuples and sequences

Tuples consist of several comma separated values , for example :

>>> t = 12345, 54321, 'hello!'
>>> t[0]
12345
>>> t
(12345, 54321, 'hello!')
>>> # Tuples may be nested:
... u = t, (1, 2, 3, 4, 5)
>>> u
((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))

As you can see , Tuples are always output in parentheses , In order to correctly express the nested structure . There may or may not be parentheses when typing , But brackets are usually necessary ( If the tuple is part of a larger expression ).

3. aggregate

A set is a set of unordered non repeating elements . Basic functions include relationship testing and de duplication .

You can use braces ({}) Create set . Be careful : If you want to create an empty collection , You have to use set() instead of {} ; The latter creates an empty dictionary , In the next section, we will introduce this data structure .

Here is a simple demonstration :

>>> basket = {
'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
>>> print(basket) # Delete duplicate 
{
'orange', 'banana', 'pear', 'apple'}
>>> 'orange' in basket # Detection member 
True
>>> 'crabgrass' in basket
False
>>> # The following demonstrates the operation of two sets 
...
>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a # a The only letter in the dictionary 
{
'a', 'r', 'b', 'c', 'd'}
>>> a - b # stay a Letters in , But not here. b in 
{
'r', 'd', 'b'}
>>> a | b # stay a or b Letters in 
{
'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
>>> a & b # stay a and b There are letters in all languages 
{
'a', 'c'}
>>> a ^ b # stay a or b Letters in , But not at the same time a and b in 
{
'r', 'd', 'b', 'm', 'z', 'l'}

Sets also support derivation :

>>> a = {
x for x in 'abracadabra' if x not in 'abc'}
>>> a
{
'r', 'd'}

4. Dictionaries

Another very useful Python The built-in data type is dictionary .

A sequence is indexed by consecutive integers , The difference is , The dictionary is indexed by keywords , Keywords can be any immutable type , It's usually a string or a number .

The best way to understand a dictionary is to think of it as Disordered keys => It's worth it aggregate . In the same dictionary , Keywords must be different from each other .

A pair of braces creates an empty dictionary :{}.

This is a simple example of dictionary use :

>>> tel = {
'jack': 4098, 'sape': 4139}
>>> tel['guido'] = 4127
>>> tel
{
'sape': 4139, 'guido': 4127, 'jack': 4098}
>>> tel['jack']
4098
>>> del tel['sape']
>>> tel['irv'] = 4127
>>> tel
{
'guido': 4127, 'irv': 4127, 'jack': 4098}
>>> list(tel.keys())
['irv', 'guido', 'jack']
>>> sorted(tel.keys())
['guido', 'irv', 'jack']
>>> 'guido' in tel
True
>>> 'jack' not in tel
False

Constructors dict() Building a dictionary directly from a list of key value pairs tuples . If there is a fixed pattern , List derivation specifies a specific key value pair :

>>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
{
'sape': 4139, 'jack': 4098, 'guido': 4127}

Besides , The dictionary can be used to create a dictionary of arbitrary values and values :

>>> {
x: x**2 for x in (2, 4, 6)}
{
2: 4, 4: 16, 6: 36}

If the keyword is just a simple string , It is sometimes more convenient to specify key value pairs with keyword parameters :

>>> dict(sape=4139, guido=4127, jack=4098)
{
'sape': 4139, 'jack': 4098, 'guido': 4127}

5. Ergodic technique

stay Dictionaries When traversing in , Keywords and corresponding values can be used items() Methods read it out at the same time

>>> knights = {
'gallahad': 'the pure', 'robin': 'the brave'}
>>> for k, v in knights.items():
... print(k, v)
...
gallahad the pure
robin the brave

stay Sequence When traversing in , Index location and corresponding value can be used enumerate() Function at the same time

>>> for i, v in enumerate(['tic', 'tac', 'toe']):
... print(i, v)
...
0 tic
1 tac
2 toe

meanwhile Traverse two or more sequences , have access to zip() Combine

>>> questions = ['name', 'quest', 'favorite color']
>>> answers = ['lancelot', 'the holy grail', 'blue']
>>> for q, a in zip(questions, answers):
... print('What is your {0}? It is {1}.'.format(q, a))
...
What is your name? It is lancelot.
What is your quest? It is the holy grail.
What is your favorite color? It is blue.

To traverse a sequence in reverse , First specify the sequence , then call reversed() function

>>> for i in reversed(range(1, 10, 2)):
... print(i)
...
9
7
5
3
1

To traverse a sequence in order , Use sorted() Function returns a sorted sequence , The original value is not modified

>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
>>> for f in sorted(set(basket)):
... print(f)
...
apple
banana
orange
pear
  • Use sorted() Function returns a sorted sequence , The original value is not modified
  • Use sort() Function returns a sorted sequence , And modify the original value

7、 ... and 、 modular

A module is a file that contains all the functions and variables you define , Its suffix is .py. Modules can be introduced by other programs , To use functions in the module . This is also used python Standard library method .

Here is a use python Examples of modules in the standard library .

#!/usr/bin/python3
# file name : using_sys.py
import sys
print(' The command line parameters are as follows :')
for i in sys.argv:
print(i)
print('\n\nPython Path is :', sys.path, '\n')
  • 1、import sys introduce python In the standard library sys.py modular ; This is the first mock exam. .
  • 2、sys.argv Is a list of command line arguments .
  • 3、sys.path Contains a Python The interpreter automatically finds a list of paths to the required modules .

1.import sentence

Want to use Python Source file , Just execute it in another source file import sentence , The grammar is as follows :

import module1[, module2[,... moduleN]

When the interpreter encounters import sentence , If the module is in the current search path it will be imported .

The search path is a list of all directories that the interpreter will search first . If you want to import modules support, You need to put the command at the top of the script :

support.py File code :

#!/usr/bin/python3
# Filename: support.py
def print_func( par ):
print ("Hello : ", par)
return

test.py introduce support modular :

test.py File code

#!/usr/bin/python3
# Filename: test.py
# The import module 
import support
# Now you can call the functions contained in the module 
support.print_func("Runoob")

A module can only be imported once , No matter how many times you execute import. This prevents the import module from being executed over and over again .

When we use import At the time of statement ,Python How does the interpreter find the corresponding file ?

This involves Python Search path for , The search path is made up of a series of directory names ,Python The interpreter looks for the introduced modules from these directories in turn .

It looks like an environment variable , in fact , You can also define the search path by defining environment variables .

The search path is in Python When compiling or installing , Installing new libraries should also change . The search path is stored in sys Module path Variable , Do a simple experiment , In the interactive interpreter , Enter the following code :

>>> import sys
>>> sys.path
['', '/usr/lib/python3.4', '/usr/lib/python3.4/plat-x86_64-linux-gnu', '/usr/lib/python3.4/lib-dynload', '/usr/local/lib/python3.4/dist-packages', '/usr/lib/python3/dist-packages']
>>>

sys.path The output is a list , The first one is an empty string ’’, Represents the current directory ( If it's printed from a script , You can see more clearly which directory it is ), That is, we implement python The directory of the interpreter ( For scripts, it's the directory where the scripts are running ).

Therefore, if a file with the same name as the module to be imported exists in the current directory like me , The module to be introduced will be shielded .

Understand the concept of search path , You can modify... In the script sys.path To introduce some modules that are not in the search path .

Now? , In the current directory of the interpreter or sys.path Create a directory in the fibo.py The file of , The code is as follows

# Fibonacci (fibonacci) Sequence module 
def fib(n): # Define the n The Fibonacci sequence of 
a, b = 0, 1
while b < n:
print(b, end=' ')
a, b = b, a+b
print()
def fib2(n): # Back to n The Fibonacci sequence of 
result = []
a, b = 0, 1
while b < n:
result.append(b)
a, b = b, a+b
return result

Then enter Python Interpreter , Use the following command to import this module :

>>> import fibo

This does not directly define fibo The function name in is written into the current symbol table , Just put the module fibo Your name is written there .

You can use the module name to access the function :

>>>fibo.fib(1000)
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
>>> fibo.fib2(100)
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
>>> fibo.__name__
'fibo'

If you're going to use a function a lot , You can assign it to a local name :

>>> fib = fibo.fib
>>> fib(500)
1 1 2 3 5 8 13 21 34 55 89 144 233 377

2.from … import sentence

Python Of from Statement allows you to import a specified part from a module into the current namespace , The grammar is as follows :

from modname import name1[, name2[, ... nameN]]

for example , To import a module fibo Of fib function , Use the following statement :

>>> from fibo import fib, fib2
>>> fib(500)
1 1 2 3 5 8 13 21 34 55 89 144 233 377

This statement will not take the whole fibo Modules are imported into the current namespace , It will only fibo Inside fib Function is introduced .


3.from … import * sentence

It is also possible to import all the contents of a module into the current namespace , Just use the following statement :

from modname import *

This provides a simple way to import all the projects in a module . However, such a declaration should not be used too much .

4. Deep module

Module except method definition , You can also include executable code . This code is usually used to initialize the module . The code is only executed when it is first imported .

Each module has its own symbol table , Within the module, it is used as a global symbol table for all functions .

therefore , The author of the module can be assured to use these global variables within the module , You don't have to worry about confusing other users' global variables .

On the other hand , When you do know what you're doing , You can also pass modname.itemname This representation is used to access functions within a module .

Modules can be imported into other modules . In a module ( Or scripts , Or somewhere else ) The first use of import To import a module , Of course, it's just a convention , It's not mandatory . The name of the imported module will be put into the symbol table of the module in the current operation .

There is another way to import , have access to import Directly into the module ( function , Variable ) Import the name into the current operation module . such as :

>>> from fibo import fib, fib2
>>> fib(500)
1 1 2 3 5 8 13 21 34 55 89 144 233 377

This import method does not put the name of the imported module in the current character table ( So in this case ,fibo This name is undefined ).

There is another way , You can put all the components in the module at one time ( function , Variable ) All names are imported into the character table of the current module :

>>> from fibo import *
>>> fib(500)
1 1 2 3 5 8 13 21 34 55 89 144 233 377

This will import all the names , But those with a single underline (_) The first name is not in this case . In most cases , Python The programmer Do not use this method , Because the names of other sources introduced , It is likely to cover the existing definition The righteous .

5.__name__ attribute

When a module is first introduced by another program , Its main program will run . If we want to introduce modules , A block in a module does not execute , We can use __name__ Property to make the block execute only when the module itself is running .

#!/usr/bin/python3
# Filename: using_name.py
if __name__ == '__main__':
print(' The program itself is running ')
else:
print(' I come from the first mock exam ')

The operation output is as follows :

$ python using_name.py
The program itself is running
$ python
>>> import using_name
I come from the first mock exam
>>>

explain : Each module has one _name__ attribute , When the value is ’_main’ when , Indicates that the module itself is running , Otherwise it's introduced .

explain :_name_ And _main_ The bottom is double underline , _ _ That's how you get rid of the space in the middle .

6.dir() function

Built in functions dir() You can find all the names defined within the module . Return as a list of strings :

>>> import fibo, sys
>>> dir(fibo)
['__name__', 'fib', 'fib2']
>>> dir(sys)
['__displayhook__', '__doc__', '__excepthook__', '__loader__', '__name__',
'__package__', '__stderr__', '__stdin__', '__stdout__',
'_clear_type_cache', '_current_frames', '_debugmallocstats', '_getframe',
'_home', '_mercurial', '_xoptions', 'abiflags', 'api_version', 'argv',
'base_exec_prefix', 'base_prefix', 'builtin_module_names', 'byteorder',
'call_tracing', 'callstats', 'copyright', 'displayhook',
'dont_write_bytecode', 'exc_info', 'excepthook', 'exec_prefix',
'executable', 'exit', 'flags', 'float_info', 'float_repr_style',
'getcheckinterval', 'getdefaultencoding', 'getdlopenflags',
'getfilesystemencoding', 'getobjects', 'getprofile', 'getrecursionlimit',
'getrefcount', 'getsizeof', 'getswitchinterval', 'gettotalrefcount',
'gettrace', 'hash_info', 'hexversion', 'implementation', 'int_info',
'intern', 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path',
'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'ps1',
'setcheckinterval', 'setdlopenflags', 'setprofile', 'setrecursionlimit',
'setswitchinterval', 'settrace', 'stderr', 'stdin', 'stdout',
'thread_info', 'version', 'version_info', 'warnoptions']

If there is no given parameter , that dir() The function lists all the names currently defined :

>>> a = [1, 2, 3, 4, 5]
>>> import fibo
>>> fib = fibo.fib
>>> dir() # Get a list of attributes defined in the current module 
['__builtins__', '__name__', 'a', 'fib', 'fibo', 'sys']
>>> a = 5 # Create a new variable 'a'
>>> dir()
['__builtins__', '__doc__', '__name__', 'a', 'sys']
>>>
>>> del a # Delete variable name a
>>>
>>> dir()
['__builtins__', '__doc__', '__name__', 'sys']
>>>

7. Standard module

Python It comes with some standard module Libraries , stay Python The library reference document will cover ( It's the back of it " Kurt's documents ").

Some modules are built directly into the parser , These are not built-in features of some languages , But he can use it very efficiently , Even system level calls are OK .

These components will be configured in different forms according to different operating systems , such as winreg Only this module will be provided Windows System .

It should be noted that there is a special module sys , It's built into every Python The parser . Variable sys.ps1 and sys.ps2 Defines the string corresponding to the main prompt and secondary prompt :

8. package

Package is a kind of management Python The form of the module namespace , use " Point module name ".

For example, the name of a module is A.B, So he means a bag A Sub modules in B .

It's like using modules , You don't have to worry about the same global variables between different modules , In the form of point module name, there is no need to worry about the duplicate names of modules between different libraries .

In this way, different authors can provide NumPy modular , Or is it Python Graphics library .

Suppose you want to design a unified processing module for sound files and data ( Or call it a " package ").

There are many different audio file formats available ( It's basically distinguished by suffixes , for example : .wav,:file:.aiff,:file:.au,), So you need to have a growing set of modules , Used to convert between different formats .

And for the audio data , There are many different operations ( Like mixing , Add echo , Add equalizer function , Create artificial stereo effects ), So you also need a set of modules that can't be written to handle these operations .

Here is a possible package structure ( In a hierarchical file system ):

sound/ Top package
__init__.py initialization sound package
formats/ File format conversion package
__init__.py
wavread.py
wavwrite.py
aiffread.py
aiffwrite.py
auread.py
auwrite.py
...
effects/ Package effect
__init__.py
echo.py
surround.py
reverse.py
...
filters/ filters subpackage
__init__.py
equalizer.py
vocoder.py
karaoke.py
...

When importing a package ,Python Will be based on sys.path To find the subdirectories contained in this package .

The directory contains only one called _init_.py Is a package , Mainly to avoid some vulgar names ( For example is called string) Carelessly affect the effective module in the search path .

In the simplest case , Put an empty one :file:_init.py That's all right. . Of course, this file can also contain some initialization code or ( It will be introduced later ) __all__ Variable assignment .

Users can import only one specific module in a package at a time , such as :

import sound.effects.echo

This will import sub modules :sound.effects.echo. He must use his full name to access :

sound.effects.echo.echofilter(input, output, delay=0.7, atten=4)

Another way to import sub modules is :

from sound.effects import echo

This will also import sub modules : echo, And he doesn't need those long prefixes , So he can use :

echo.echofilter(input, output, delay=0.7, atten=4)

Another change is to import a function or variable directly :

from sound.effects.echo import echofilter

alike , This method will import sub modules : echo, And you can use his echofilter() function :

echofilter(input, output, delay=0.7, atten=4)

Pay attention when using from package import item In this form , Corresponding item It can be a sub module in the package ( subpackage ), Or any other name in the package , Like functions , Class or variable .

import Grammar will first put item As a package definition name , If not , Then try to import according to a module . If you haven't found it yet , Throw a :exc:ImportError abnormal .

conversely , If you use the form import item.subitem.subsubitem This form of import , Except for the last term , All have to be bags , The last item can be a module or a package , No, but class , The name of a function or variable .

9. Import... From a package *

If we use from sound.effects import * What will happen ?

Python Will enter the file system , Find all the sub modules in this package , Then import them one by one .

But this method is in Windows The work on the platform is not very good , because Windows Is a case insensitive system .

stay Windows On the platform , We can't be sure that one is called ECHO.py The file imported as a module is echo still Echo, Or is it ECHO.

To solve this problem , We just need to provide an accurate package index .

The import statement follows the following rules : If the package definition file init.py There is one called all List variables of , So in use from package import * All the names in this list will be imported as package contents .

As the author of the package , Don't forget to guarantee after updating the package all Also updated .

The following examples are in file:sounds/effects/init.py Contains the following code :

__all__ = ["echo", "surround", "reverse"]

This means that when you use from sound.effects import * In this way , You can only import the three sub modules in the package .

If all There's really no definition , So use **from sound.effects import *** When it comes to this grammar , The package will not be imported sound.effects Any sub module in . He just put the bag sound.effects And all the content defined in it ( It's possible to run __init__.py Initialization code defined in ).

This will turn init.py Import all the names defined inside . And it will not destroy all the explicitly specified modules we imported before this sentence . Take a look at this code :

import sound.effects.echo
import sound.effects.surround
from sound.effects import *

In this case , In execution from…import front , package sound.effects Medium echo and surround Modules are imported into the current namespace .( Of course, if defined all Even more no problem )

Usually we do not advocate the use of ***** This method is used to import modules , Because this approach often leads to a reduction in the readability of the code . But it really saves a lot of keystrokes , And some modules are designed to be imported only through specific methods .

remember , Use from Package import specific_submodule This method can never be wrong . in fact , This is also the recommended method . Unless the sub module you want to import may have the same name as the sub module of other packages .

If the package is a sub package in the structure ( For example, in this example, for the package sound Come on ), And you want to import the brother package ( Packages of the same level ) You have to use the import absolute path to import . such as , If the module sound.filters.vocoder To use a package sound.effects Module in echo, You have to write from sound.effects import echo.

from . import echo
from .. import formats
from ..filters import equalizer

Whether implicit or explicit, the relative Import starts from the current module . The name of the main module is always "main", One Python The main module of the application , You should always use absolute path references .

The package also provides an additional attribute __path__. This is a list of directories , Each directory contained in it has a service for this package __init__.py, You have to be in other __init__.py Defined before execution . You can modify this variable , Used to affect the modules and sub packages contained in the package .

This feature is not commonly used , It is generally used to expand the modules in the package .

8、 ... and 、 Input and output

1, Output format beautification

Python Two ways to output values : Expressions and print() function .

The third way is to use file objects write() Method , Standard output files can be used sys.stdout quote .

If you want the output to be more diverse , have access to str.format() Function to format the output value .

If you want to convert the output value to a string , have access to repr() or str() Function to implement .

  • str(): Function returns a user-friendly expression .
  • repr(): Produce an interpreter readable form of expression .repr() The function can escape special characters in a string
>>> s = 'Hello, Runoob'
>>> str(s)
'Hello, Runoob'
>>> repr(s)
"'Hello, Runoob'"
>>> str(1/7)
'0.14285714285714285'
>>> x = 10 * 3.25
>>> y = 200 * 200
>>> s = 'x The value of is : ' + repr(x) + ', y The value of is :' + repr(y) + '...'
>>> print(s)
x The value of is : 32.5, y The value of is :40000...
>>> # repr() The function can escape special characters in a string 
... hello = 'hello, runoob\n'
>>> hellos = repr(hello)
>>> print(hellos)
'hello, runoob\n'
>>> # repr() The parameter of can be Python Any object of 
... repr((x, y, ('Google', 'Runoob')))
"(32.5, 40000, ('Google', 'Runoob'))"

There are two ways to output a table of squares and cubes :

>>> for x in range(1, 11):
... print(repr(x).rjust(2), repr(x*x).rjust(3), end=' ')
... # Note the previous line 'end' Use 
... print(repr(x*x*x).rjust(4))
...
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
6 36 216
7 49 343
8 64 512
9 81 729
10 100 1000
>>> for x in range(1, 11):
... print('{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x))
...
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
6 36 216
7 49 343
8 64 512
9 81 729
10 100 1000

** Be careful :** In the first example , The space between each column is determined by print() add to .

  • This example shows the string object's str.rjust(width) Method , It can put strings to the right , And fill in the space on the left to the length width New string of .

  • ljust(width) You can keep the string to the left , And fill in the space on the right

  • center(width) You can center the string , Fill in the blanks on the left and right

    These methods don't write anything , They just return new strings .

  • Another way zfill(width), It will fill the left side of the number with 0( To the specified width ), As shown below :

>>> '12'.zfill(5)
'00012'
>>> '-3.14'.zfill(7)
'-003.14'
>>> '3.14159265359'.zfill(5)
'3.14159265359'

2.str.format() Use

>>> print('{} website : "{}!"'.format(' Novice tutorial ', 'www.runoob.com'))
Rookie tutorial website : "www.runoob.com!"

Brackets and the characters inside them ( It's called a formatted field ) Will be format() Parameter substitution in .

Usage mode :

(1) stay The number in parentheses is used to point to the incoming object in format() Position in , As shown below :

>>> print('{0} and {1}'.format('Google', 'Runoob'))
Google and Runoob
>>> print('{1} and {0}'.format('Google', 'Runoob'))
Runoob and Google

(2) If in format() Used in Key parameters , Then their values point to the parameter with that name .

>>> print('{name} website : {site}'.format(name=' Novice tutorial ', site='www.runoob.com'))
Rookie tutorial website : www.runoob.com

(3) Location and keyword parameters can be arbitrarily combined :

>>> print(' Site list {0}, {1}, and {other}.'.format('Google', 'Runoob', other='Taobao'))
Site list Google, Runoob, and Taobao.

!a ( Use ascii()), !s ( Use str()) and !r ( Use repr()) It can be used for Convert a value before formatting it :

>>> import math
>>> print(' Constant PI The value of is approximately : {}.'.format(math.pi))
Constant PI The value of is approximately : 3.141592653589793.
>>> print(' Constant PI The value of is approximately : {!r}.'.format(math.pi))
Constant PI The value of is approximately : 3.141592653589793.

Fill and align

^<> Respectively mean center 、 Align left 、 Right alignment , Width of back band
print('{:^30}'.format("zhangsan")) # In the middle 
print('{:>30}'.format("zhangsan")) # Right alignment 
print('{:<30}'.format("zhangsan")) # Align left 

Field length ( The length from leftmost to rightmost )

stay : Then pass in an integer , You can guarantee that the field has at least so much width . Useful for beautifying tables .

>>> table = {
'Google': 1, 'Runoob': 2, 'Taobao': 3}
>>> for name, number in table.items():
... print('{0:10} ==> {1:10d}'.format(name, number))
...
Google ==> 1
Runoob ==> 2
Taobao ==> 3

Precision control :.nf

print('{:.2f}'.format(3.14159))
result :3.14
Keep two decimal places , Round the last two digits

Binary conversion ,b o d x They represent two 、 8、 ... and 、 Ten 、 Hexadecimal

print('{:b}'.format(20))
print('{:o}'.format(20))
print('{:d}'.format(20))
print('{:x}'.format(20))

optional : And format identifier can follow the field name . This allows for better formatting of values . The following example will Pi Keep to three decimal places :

>>> import math
>>> print(' Constant PI The value of is approximately {0:.3f}.'.format(math.pi))
Constant PI The value of is approximately 3.142.

If you have a long formatted string , And you don't want to separate them , So it's good to use variable names instead of locations when formatting .

The easiest way is to pass in a dictionary , And then use square brackets [] To access the key value :

>>> table = {
'Google': 1, 'Runoob': 2, 'Taobao': 3}
>>> print('Runoob: {0[Runoob]:d}; Google: {0[Google]:d}; Taobao: {0[Taobao]:d}'.format(table))
Runoob: 2; Google: 1; Taobao: 3

It can also be done through table Variable before using ** To achieve the same function :

>>> table = {
'Google': 1, 'Runoob': 2, 'Taobao': 3}
>>> print('Runoob: {Runoob:d}; Google: {Google:d}; Taobao: {Taobao:d}'.format(**table))
Runoob: 2; Google: 1; Taobao: 3

3. Old style string formatting

% Operators can also implement string formatting . It takes the parameter on the left as something like sprintf() The format string of , And put the one on the right into , Then return the formatted string . for example :

>>> import math
>>> print(' Constant PI The value of is approximately :%5.3f.' % math.pi)
Constant PI The value of is approximately :3.142.

because str.format() It's a relatively new function , Most of the Python The code still uses % The operator . But because this old-fashioned formatting will eventually be removed from the language , It should be used more str.format().

4. Read keyboard input

Python Provides input() Built in functions Read in a line of text from standard input , The default standard input is the keyboard .

#!/usr/bin/python3
str = input(" Please enter :");
print (" What you input is : ", str)

5. Read and write documents

open() Will return a file object , The basic syntax is as follows :

open(filename, mode)
  • filename: String value containing the name of the file you want to access .
  • mode: Determines the mode of opening files : read-only , write in , Supplemental . All available values are shown in the complete list below . This parameter is optional , The default file access mode is read-only .

Open the full list of files in different modes :

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 .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 .

The following example writes a string to a file foo.txt in :

#!/usr/bin/python3
# Open a file 
f = open("/tmp/foo.txt", "w")
f.write( "Python It's a very good language .\n Yes , It's really good !!\n" )
# Close open files 
f.close()

6. Method of file object

The remaining examples in this section assume that you have created a named f The file object of .

f.read()---- Read all or a specified number of contents , As a string

To read the contents of a file , call f.read(size), This will read a certain amount of data , Then return... As a string or byte object .

size Is an optional number type parameter . When size Ignored or negative , Then all the contents of the file will be read and returned .

The following example assumes that the file foo.txt Already exists ( In the example above ):

#!/usr/bin/python3
# Open a file 
f = open("/tmp/foo.txt", "r")
str = f.read()
print(str)
# Close open files 
f.close()

f.readline()— Read the string that returns one line of content line by line

f.readline() A separate line will be read from the file . The newline character is ‘\n’.f.readline() If you return an empty string , The description has been read to the last line .

Read the instance line by line :

with open(file_path, encoding='utf-8') as file_obj:
line = file_obj.readline()
while line != '':
print(line)
line = file_obj.readline()

f.readlines()— Read line by line , Return the contents of each line and store them in the list

f.readlines() All lines contained in the file... Will be returned . The file will be read line by line and stored in a list at one time

If optional parameters are set sizehint, Then read the specified length of bytes , And divide these bytes into lines .

with open(file_path, encoding='utf-8') as file_obj:
lines = file_obj.readlines()
for line in lines:
print(line)

Iterate over a file object and read each line :

#!/usr/bin/python3
# Open a file 
f = open("/tmp/foo.txt", "r")
for line in f:
print(line, end='')
# Close open files 
f.close()

This method is very simple , But it doesn't provide a good control . Because the two mechanisms are different , It's better not to mix .

f.write()

f.write(string) take string Write to a file , Then return the number of characters written .****

#!/usr/bin/python3
# Open a file 
f = open("/tmp/foo.txt", "w")
num = f.write( "Python It's a very good language .\n Yes , It's really good !!\n" )
print(num)
# Close open files 
f.close()

If you want to write something that is not a string , Then it will need to be converted first :

#!/usr/bin/python3
# Open a file 
f = open("/tmp/foo1.txt", "w")
value = ('www.runoob.com', 14)
s = str(value)
f.write(s)
# Close open files 
f.close()
####### result , The contents of the document :
('www.runoob.com', 14)

f.tell()

f.tell() Returns the current location of the file object , It is the number of bytes from the beginning of the file .

f.seek()

If you want to change the current location of the file , have access to f.seek(offset, from_what) function .

from_what Value , If it is 0 Beginning of expression , If it is 1 Indicates the current location , 2 Indicates the end of the file , for example :

  • seek(x,0) : Move from the starting position, i.e. the first character of the first line of the file x Characters
  • seek(x,1) : Indicates to move backward from the current position x Characters
  • seek(-x,2): To move forward from the end of a file x Characters

from_what The default value is 0, The beginning of the document . Here's a complete example :

>>> f = open('/tmp/foo.txt', 'rb+')
>>> f.write(b'0123456789abcdef')
16
>>> f.seek(5) # Move to the sixth byte of the file 
5
>>> f.read(1)
b'5'
>>> f.seek(-3, 2) # Move to the penultimate byte of the file 
13
>>> f.read(1)
b'd'

f.close()

In a text file ( Those open file modes don't have b Of ), It will only be positioned relative to the start of the file .

When you finish processing a file , call f.close() To close files and free system resources , If you try to call the file again , An exception will be thrown .

>>> f.close()
>>> f.read()
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ValueError: I/O operation on closed file

When processing a file object , Use with Keywords are a great way to . At the end , It will help you close the file correctly . And it's better to write than try - finally The sentence block should be short :

>>> with open('/tmp/foo.txt', 'r') as f:
... read_data = f.read()
>>> f.closed
True

There are other methods for file objects , Such as isatty() and trucate(), But these are usually less used .

7.pickle modular

import pickle

python Of pickle The module implements the basic data sequence and deserialization .

  • adopt pickle Module serialization operation we can save the object information running in the program to a file , Permanent storage .
  • adopt pickle Deserialization of modules , We were able to create objects from the file that were last saved by the program .

Basic interface :

pickle.dump(obj, file, [,protocol])

With pickle This object , You can be right file Open as read :

x = pickle.load(file)

** annotation :** from file Read a string in the , And reconstruct it into the original python object .

file: Class file object , Yes read() and readline() Interface .

Instance of a :

#!/usr/bin/python3
import pickle
# Use pickle Module saves data objects to a file 
data1 = {
'a': [1, 2.0, 3, 4+6j],
'b': ('string', u'Unicode string'),
'c': None}
selfref_list = [1, 2, 3]
selfref_list.append(selfref_list)
output = open('data.pkl', 'wb')
# Pickle dictionary using protocol 0. Use agreement 0 Serialization Dictionary 
pickle.dump(data1, output)
# Pickle the list using the highest protocol available. Use agreement -1 Serialized list 
pickle.dump(selfref_list, output, -1)
output.close()

Example 2 :

#!/usr/bin/python3
import pprint, pickle
# Use pickle Module refactoring from file python object 
pkl_file = open('data.pkl', 'rb')
data1 = pickle.load(pkl_file)
pprint.pprint(data1)
data2 = pickle.load(pkl_file)
pprint.pprint(data2)
pkl_file.close()

Nine 、File

1.open() Method

Python open() Method is used to open a file , And return the file object , This function is used for processing files , If the file cannot be opened , Will throw out OSError.

** Be careful :** Use open() Methods must ensure that the file object is closed , That is to call close() Method .

open() A function usually takes two arguments : file name (file) And pattern (mode).

open(file, mode='r')

The complete syntax is :

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

Parameter description :

  • file: It's necessary , File path ( Relative or absolute paths ).
  • mode: Optional , File open mode . Refer to section of Chapter VIII 6 section
  • buffering: Set the buffer
  • encoding: In general use utf8
  • errors: An error level
  • newline: Distinguish line breaks
  • closefd: Incoming file Parameter type
  • opener: Set custom opener , The return value of the opener must be an open file descriptor .

2.file Functions commonly used by objects

file Object use open Function to create , The following table lists them file Functions commonly used by objects :

Serial number Method and description 1file.close() Close file . After closing, the file can no longer be read or written .2file.flush() Refresh file internal buffer , Write the data of the internal buffer directly to the file , Instead of passively waiting for the output buffer to write .3file.fileno() Returns an integer file descriptor (file descriptor FD integer ), It can be used as os Modular read Methods and other bottom operations .4file.isatty() If the file is connected to a terminal device, return True, Otherwise return to False.5file.next()**Python 3 Medium File Object does not support next() Method .** Return to the next line of the file .6[file.read(size]) Read the specified number of bytes from the file , Read all if not given or negative .7[file.readline(size]) Read entire line , Include “\n” character .8[file.readlines(sizeint]) Read all the lines and return the list , If given sizeint>0, The sum of the returns is about sizeint Byte line , The actual read value may be greater than sizeint more , Because the buffer needs to be filled .9[file.seek(offset, whence]) Move the file read pointer to the specified location 10file.tell() Return to the current location of the file .11[file.truncate(size]) Start with the first character of the file , Truncate the file to size Characters , nothing size Indicates truncation from current position ; All characters after truncation are deleted , among windows Line feed under the system represents 2 Character size .12file.write(str) Write string to file , What is returned is the length of the characters written .13file.writelines(sequence) Write a list of sequence strings to the file , If you need a new line, you need to add a new line character for each line .

Ten 、OS File or directory method

import os

os Module provides a very rich way to handle files and directories . The common methods are shown in the following table :

Serial number Method and description 1os.access(path, mode) Verify authority mode 2os.chdir(path) Change the current working directory 3os.chflags(path, flags) Set the path's flag as a numeric flag .4os.chmod(path, mode) Change permissions 5os.chown(path, uid, gid) Change file owner 6os.chroot(path) Change the root of the current process 7os.close(fd) Close the file descriptor fd8os.closerange(fd_low, fd_high) Close all file descriptors , from fd_low ( contain ) To fd_high ( It doesn't contain ), Mistakes will be ignored 9os.dup(fd) Copy file descriptors fd10os.dup2(fd, fd2) Put a file descriptor fd Copy to another fd211os.fchdir(fd) Change the current working directory through the file descriptor 12os.fchmod(fd, mode) Change access to a file , The file consists of parameters fd Appoint , Parameters mode yes Unix File access rights under .13os.fchown(fd, uid, gid) Modify the ownership of a file , This function modifies the user of a file ID User group ID, This file is made up of file descriptors fd Appoint .14os.fdatasync(fd) Force file to disk , This file is made up of file descriptors fd Appoint , But don't force the status information of the file to be updated .15[os.fdopen(fd, mode[, bufsize]]) Through file descriptors fd Create a file object , And return the file object 16os.fpathconf(fd, name) Returns the system configuration information of an open file .name The value configured for the retrieved system , It might be a string that defines the system value , These names are specified in many standards (POSIX.1, Unix 95, Unix 98, And other ).17os.fstat(fd) Return file descriptor fd The state of , image stat().18os.fstatvfs(fd) Return include file descriptor fd Information about the file system of ,Python 3.3 Equivalent to statvfs().19os.fsync(fd) Force the file descriptor to fd Of files written to the hard disk .20os.ftruncate(fd, length) Crop file descriptors fd Corresponding file , So it can't exceed the maximum file size .21os.getcwd() Return to the current working directory 22os.getcwdb() Returns the... Of the current working directory Unicode object 23os.isatty(fd) If the file descriptor fd It's open , At the same time tty(-like) Equipment connection , Then return to true, otherwise False.24os.lchflags(path, flags) Set the path's flag as a numeric flag , similar chflags(), But there are no soft links 25os.lchmod(path, mode) Modify connection file permissions 26os.lchown(path, uid, gid) Change file owner , similar chown, But don't track links .27os.link(src, dst) Create a hard link , Named parameter dst, Point to parameters src28os.listdir(path) return path The specified folder contains a list of files or folder names .29os.lseek(fd, pos, how) Set the file descriptor fd The current position is pos, how Way to modify : SEEK_SET perhaps 0 Set calculated from file pos; SEEK_CUR perhaps 1 From the current position ; os.SEEK_END perhaps 2 From the end of the file . stay unix,Windows Effective in 30os.lstat(path) image stat(), But there are no soft links 31os.major(device) Extract the device from the original device number major number ( Use stat Medium st_dev perhaps st_rdev field).32os.makedev(major, minor) With major and minor The equipment number forms an original equipment number 33[os.makedirs(path, mode]) Recursive folder creation function . image mkdir(), But all that was created intermediate-level Folder needs to contain subfolders .34os.minor(device) Extract the device from the original device number minor number ( Use stat Medium st_dev perhaps st_rdev field ).35[os.mkdir(path, mode]) In numbers mode Of mode Create a file called path Folder . default mode yes 0777 ( octal ).36[os.mkfifo(path, mode]) Create named pipes ,mode Is the number , The default is 0666 ( octal )37[os.mknod(filename, mode=0600, device]) Create a file called filename File system nodes ( file , Device special file or name pipe).38[os.open(file, flags, mode]) Open a file , And set the required open options ,mode Parameters are optional 39os.openpty() Open a new pseudo terminal pair . return pty and tty File descriptor for .40os.pathconf(path, name) Return the system configuration information of related files .41os.pipe() Create a pipe . Returns a pair of file descriptors (r, w) Read and write, respectively 42[os.popen(command, mode[, bufsize]]) From a command Open a pipe 43os.read(fd, n) From file descriptor fd Read the most n Bytes , Returns the string containing the bytes read , File descriptor fd The corresponding file has reached the end , Returns an empty string .44os.readlink(path) Return the file pointed to by the soft link 45os.remove(path) The deletion path is path The file of . If path It's a folder , Will throw out OSError; Check out rmdir() Delete one directory.46os.removedirs(path) Recursively delete directories .47os.rename(src, dst) Rename a file or directory , from src To dst48os.renames(old, new) Recursively rename the directory , You can also rename the document .49os.rmdir(path) Delete path Empty directory specified , If the directory is not empty , Then throw a OSError abnormal .50os.stat(path) obtain path Information about the specified path , Function equivalent to C API Medium stat() system call .51[os.stat_float_times(newvalue]) decision stat_result Whether or not to float Object display timestamp 52os.statvfs(path) Get file system statistics for the specified path 53os.symlink(src, dst) Create a soft link 54os.tcgetpgrp(fd) Return to terminal fd( One by os.open() Open file descriptor returned ) Associated process groups 55os.tcsetpgrp(fd, pg) Settings and terminals fd( One by os.open() Open file descriptor returned ) The associated process group is pg.56os.tempnam([dir[, prefix]]) **Python3 Has been deleted from .** Returns the unique pathname used to create the temporary file .57os.tmpfile() **Python3 Has been deleted from .** Return an open mode as (w+b) The file object of . This file object has no folder entry , There is no file descriptor , Will automatically delete .58os.tmpnam() **Python3 Has been deleted from .** Return a unique path for creating a temporary file 59os.ttyname(fd) Returns a string , It represents with the file descriptor fd Associated terminal devices . If fd There is no associated terminal device , An exception is raised .60os.unlink(path) Delete file path 61os.utime(path, times) Returns the specified path File access and modification time .62[os.walk(top, topdown=True[, οnerrοr=None[, followlinks=False]]]) Output the filename in the folder by swimming through the tree , Up or down .63os.write(fd, str) Write string to file descriptor fd in . Returns the length of the string actually written 64os.path modular Get the attribute information of the file .65os.pardir() Get the parent directory of the current directory , Displays the directory name as a string .

11、 ... and 、 Errors and exceptions

Python There are two kinds of mistakes that are easy to recognize : Grammatical errors and exceptions .

Python **assert( Assertion )** Used to determine an expression , In the expression, the condition is false Trigger exception when .

1. Grammar mistakes

Python We call it parsing error , It's what beginners often encounter , The following example

>>> while True print('Hello world')
File "<stdin>", line 1, in ?
while True print('Hello world')
^
SyntaxError: invalid syntax

In this case , function print() It was detected that there was a mistake , It's missing a colon in front of it : .

The parser points out the wrong line , And marked a small arrow in the wrong place that was first found .

2. abnormal

Even if Python The syntax of the program is correct , When it's running , There is also the possibility of mistakes . Errors detected during runtime are called exceptions .

Most exceptions are not handled by the program , All in the form of error messages :

>>> 10 * (1/0) # 0 Not as a divisor , An exception 
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ZeroDivisionError: division by zero
>>> 4 + spam*3 # spam Undefined , An exception 
Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: name 'spam' is not defined
>>> '2' + 2 # int Cannot be associated with str Add up , An exception 
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str

Exceptions come in different types , These types are printed as part of the message : The types in the examples are ZeroDivisionError,NameError and TypeError.

The first part of the error message shows the context in which the exception occurred , And display the specific information in the form of call stack .

3. exception handling

try/except

Exception catching can be used try/except sentence .

In the following example , Let the user enter a legal integer , But allow the user to interrupt the program ( Use Control-C Or the method provided by the operating system ). User interrupted information will trigger a KeyboardInterrupt abnormal .

while True:
try:
x = int(input(" Please enter a number : "))
break
except ValueError:
print(" You are not entering numbers , Please try typing... Again !")

try The statement works as follows ;

  • First , perform try Clause ( In keywords try And keywords except The sentence between ).
  • If no exceptions occur , Ignore except Clause ,try End after Clause execution .
  • If in execution try An exception occurred during clause , that try The rest of the clause will be ignored . If the type of exception and except The following names match , So the corresponding except Clause will be executed .
  • If an exception is not associated with anything except matching , Then this exception will be passed to the upper level try in .

One try The statement may contain more than one except Clause , To handle different specific exceptions . At most one branch will be executed .

The handler will only target the corresponding try Exception in Clause , Not the others try Exception in handler for .

One except Clause can handle multiple exceptions at the same time , These exceptions will be placed in parentheses as a tuple , for example :

except (RuntimeError, TypeError, NameError):
pass

the last one except Clause to ignore the name of the exception , It will be used as a wildcard . You can use this method to print an error message , Then throw the exception again .

import sys
try:
f = open('myfile.txt')
s = f.readline()
i = int(s.strip())
except OSError as err:
print("OS error: {0}".format(err))
except ValueError:
print("Could not convert data to an integer.")
except:
print("Unexpected error:", sys.exc_info()[0])
raise

try/except…else

try/except There is also an optional else Clause , If you use this clause , Then we must On all except After Clause .

else Clause will be try Clause is executed when no exception occurs .

The following examples are in try Statement to determine whether the file can be opened , If the file is opened normally without exception, execute else Part of the sentence , Read file contents :

for arg in sys.argv[1:]:
try:
f = open(arg, 'r')
except IOError:
print('cannot open', arg)
else:
print(arg, 'has', len(f.readlines()), 'lines')
f.close()

Use else Clause is better than putting all statements in try The clause is better , This can avoid some unexpected , and except An exception that can't be caught .

Exception handling doesn't just deal with those that happen directly in try Exception in clause , It can also handle functions invoked in clauses ( Even indirectly called functions ) The exception thrown in . for example :

>>> def this_fails():
x = 1/0
>>> try:
this_fails()
except ZeroDivisionError as err:
print('Handling run-time error:', err)
Handling run-time error: int division or modulo by zero

try-finally sentence

try-finally Statement will execute the last code whether or not an exception occurs .

In the following example finally Statement executes whether or not an exception occurs :

try:
runoob()
except AssertionError as error:
print(error)
else:
try:
with open('file.log') as file:
read_data = file.read()
except FileNotFoundError as fnf_error:
print(fnf_error)
finally:
print(' this sentence , Whether or not an exception occurs, it will execute .')

4. Throw an exception

Python Use raise Statement throws a specified exception .

raise The syntax is as follows :

raise [Exception [, args [, traceback]]]

Here is an example if x Greater than 5 Trigger the exception :

x = 10
if x > 5:
raise Exception('x Not greater than 5.x The value of is : {}'.format(x))

Executing the above code will trigger an exception :

Traceback (most recent call last):
File "test.py", line 3, in <module>
raise Exception('x Not greater than 5.x The value of is : {}'.format(x))
Exception: x Not greater than 5.x The value of is : 10

raise The only parameter that specifies the exception to be thrown . It must be an exception instance or an exception class ( That is to say Exception Subclasses of ).

If you just want to know if this throws an exception , Don't want to deal with it , So a simple raise Statement can throw it out again .

>>> try:
raise NameError('HiThere')
except NameError:
print('An exception flew by!')
raise
An exception flew by!
Traceback (most recent call last):
File "<stdin>", line 2, in ?
NameError: HiThere

5. User defined exception

You can have your own exceptions by creating a new exception class . Exception classes inherit from Exception class , Can inherit directly , Or indirectly , for example :

>>> class MyError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
>>> try:
raise MyError(2*2)
except MyError as e:
print('My exception occurred, value:', e.value)
My exception occurred, value: 4
>>> raise MyError('oops!')
Traceback (most recent call last):
File "<stdin>", line 1, in ?
__main__.MyError: 'oops!'

In this case , class Exception default _init_() Be overwritten .

When it is possible to create a module to throw many different exceptions , A common practice is for this package Create a basic exception class , Then create different subclasses for different error situations based on this base class :

class Error(Exception):
"""Base class for exceptions in this module."""
pass
class InputError(Error):
"""Exception raised for errors in the input. Attributes: expression -- input expression in which the error occurred message -- explanation of the error """
def __init__(self, expression, message):
self.expression = expression
self.message = message
class TransitionError(Error):
"""Raised when an operation attempts a state transition that's not allowed. Attributes: previous -- state at beginning of transition next -- attempted new state message -- explanation of why the specific transition is not allowed """
def __init__(self, previous, next, message):
self.previous = previous
self.next = next
self.message = message

Most of the names of exceptions are "Error" ending , It's the same as the standard exception naming .

6. Define cleanup behavior

try Statement has another optional clause , It defines the cleanup behavior that will be performed in any case . for example :

>>> try:
... raise KeyboardInterrupt
... finally:
... print('Goodbye, world!')
...
Goodbye, world!
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
KeyboardInterrupt

The above examples do not matter try Is there any exception in the clause ,finally Clause will execute .

If an exception is in try In Clause ( Or in except and else In Clause ) To be thrown out , and There's nothing except Stop it , So this exception will be in finally Clause is thrown after execution .

Here's a more complex example ( In the same try The sentence contains except and finally Clause ):

>>> def divide(x, y):
try:
result = x / y
except ZeroDivisionError:
print("division by zero!")
else:
print("result is", result)
finally:
print("executing finally clause")
>>> divide(2, 1)
result is 2.0
executing finally clause
>>> divide(2, 0)
division by zero!
executing finally clause
>>> divide("2", "1")
executing finally clause
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 3, in divide
TypeError: unsupported operand type(s) for /: 'str' and 'str'

7. Predefined cleanup behavior

Some objects define standard cleanup behavior , Whether or not the system successfully uses it , Once you don't need it , Then the standard clean-up will be carried out .

This example shows trying to open a file , Then print the content to the screen :

for line in open("myfile.txt"):
print(line, end="")

The problem with the above code is , When the execution is finished , The file will remain open , Not shut down .

key word with Statement can ensure that objects such as files will execute their cleanup methods correctly after use :

with open("myfile.txt") as f:
for line in f:
print(line, end="")

After the above code is executed , Even if something goes wrong in the process , file f Always close .

8. assert( Assertion )

Python assert( Assertion ) Used to determine an expression , In the expression, the condition is false Trigger exception when .

Assertions can directly return errors when conditions are not met , You don't have to wait for the program to crash , For example, our code can only be in Linux Running under the system , You can first judge whether the current system meets the conditions .

The syntax is as follows :

assert expression

Equivalent to :

if not expression:
raise AssertionError

assert You can also follow the parameter :

assert expression [, arguments]

Equivalent to :

if not expression:
raise AssertionError(arguments)

The following is a assert Using examples :

>>> assert True # Condition is true Normal execution 
>>> assert False # Condition is false An exception 
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError
>>> assert 1==1 # Condition is true Normal execution 
>>> assert 1==2 # Condition is false An exception 
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError
>>> assert 1==2, '1 It's not equal to 2'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError: 1 It's not equal to 2
>>>

The following example determines whether the current system is Linux, If the conditions are not met, an exception will be triggered directly , You don't have to execute the next code :

import sys
assert ('linux' in sys.platform), " This code can only be used in Linux perform "

Twelve 、 object-oriented

Python It has been an object-oriented language since the beginning of design , Because of that , stay Python It's easy to create a class and object in .

1. Introduction of object oriented technology

  • class (Class): A collection of objects with the same properties and methods . It defines the properties and methods that are common to each object in the collection . Object is an instance of a class .
  • ** Method :** Functions defined in class .
  • ** Class variables :** Class variables are common to the entire instantiated object . Class variables are defined in the class and outside the function body . Class variables are usually not used as instance variables .
  • ** Data member :** Class variables or instance variables are used to process data related to a class and its instance objects .
  • ** Method rewriting :** If the method inherited from the parent class does not meet the needs of the child class , It can be rewritten , This process is called method coverage (override), Also known as method rewriting .
  • ** local variable :** Variables defined in methods , Class that only works on the current instance .
  • ** Instance variables :** In the declaration of a class , Properties are represented by variables , This variable is called instance variable , An instance variable is a function of self Decorated variable .
  • ** Inherit :** That is, a derived class (derived class) Inherited base class (base class) Fields and methods for . Inheritance also allows the object of a derived class to be treated as a base class object . for example , There is such a design : One Dog Object of type derived from Animal class , This is a simulation " It's a (is-a)" Relationship ( Case diagram ,Dog It's a Animal).
  • ** Instantiation :** Create an instance of a class , Class specific objects .
  • ** object :** Data structure instance defined by class . Object contains two data members ( Class variables and instance variables ) And methods .

Compared with other programming languages ,Python Class mechanism is added without adding new syntax and semantics as much as possible .

Python The classes in provide all the basic functions of object-oriented programming : Class inheritance mechanism allows multiple base classes , Derived classes can override any method in the base class , Method can call a method with the same name in the base class .

Objects can contain any number and type of data .

2. Class definition

The syntax is as follows :

class ClassName:
<statement-1>
.
.
.
<statement-N>

After class instantiation , You can use its properties , actually , After creating a class , You can access its properties through the class name .

3. Class object

Class objects support two operations : Property references and instantiations .

Property references use and Python All properties in reference to the same standard syntax :obj.name.

After the class object is created , All names in the class namespace are valid property names . So if the class definition is like this :

#!/usr/bin/python3
class MyClass:
""" A simple class instance """
i = 12345
def f(self):
return 'hello world'
# Instantiate the class 
x = MyClass()
# Access class properties and methods 
print("MyClass Attributes of a class i by :", x.i)
print("MyClass Class method f Output is :", x.f())

The above creates a new class instance and assigns the object to a local variable x,x Empty object .

The output of the above program is :

MyClass Attributes of a class i by : 12345
MyClass Class method f Output is : hello world

Class has a name _init_() Special method ( Construction method ), This method is called automatically when the class is instantiated , Like this :

def __init__(self):
self.data = []

Class definition _init() Method , The instantiation of the class will automatically call _ init() Method . Instantiate the class as follows MyClass, Corresponding _init() Method will be called :

x = MyClass()

Of course , _init() Method can have parameters , Parameters through _init_() Passed to the instantiation operation of the class . for example :

#!/usr/bin/python3
class Complex:
def __init__(self, realpart, imagpart):
self.r = realpart
self.i = imagpart
x = Complex(3.0, -4.5)
print(x.r, x.i) # Output results :3.0 -4.5

self Represents an instance of a class , Not class

There is only one special difference between a class method and a normal function —— They have to have an extra First parameter name , By convention its name is self.

class Test:
def prt(self):
print(self)
print(self.__class__)
t = Test()
t.prt()

The execution result of the above example is :

<__main__.Test instance at 0x100771878>
__main__.Test

It is obvious from the execution results ,self Represents an instance of a class , Represents the address of the current object , and self.class Point to class .

self No python keyword , We'll replace him with runoob It can also be executed normally :

class Test:
def prt(runoob):
print(runoob)
print(runoob.__class__)
t = Test()
t.prt()

4. Class method

Inside the class , Use def Keyword to define a method , Different from general function definition , Class method must contain parameters self, And it's the first parameter ,self Represents an instance of a class .

#!/usr/bin/python3
# Class definition 
class people:
# Define basic attributes 
name = ''
age = 0
# Define private properties , Private properties cannot be accessed directly outside the class 
__weight = 0
# Define construction method 
def __init__(self,n,a,w):
self.name = n
self.age = a
self.__weight = w
def speak(self):
print("%s say : I %d year ." %(self.name,self.age))
# Instantiate the class 
p = people('runoob',10,30)
p.speak()

The output of the above program is :

runoob say : I 10 year .

5. Inherit

Python Class inheritance is also supported , If a language does not support inheritance , Classes have no meaning . The definition of a derived class is as follows :

class DerivedClassName(BaseClassName):
<statement-1>
.
.
.
<statement-N>

Subclass ( Derived class DerivedClassName) Will inherit the parent class ( Base class BaseClassName) Properties and methods of .

BaseClassName( The base class name in the instance ) Must be in the same scope as the derived class definition . Except class , You can also use expressions , This is useful when the base class is defined in another module :

class DerivedClassName(modname.BaseClassName):
#!/usr/bin/python3
# Class definition 
class people:
# Define basic attributes 
name = ''
age = 0
# Define private properties , Private properties cannot be accessed directly outside the class 
__weight = 0
# Define construction method 
def __init__(self,n,a,w):
self.name = n
self.age = a
self.__weight = w
def speak(self):
print("%s say : I %d year ." %(self.name,self.age))
# Single inheritance example 
class student(people):
grade = ''
def __init__(self,n,a,w,g):
# Call the constructor of the parent class 
people.__init__(self,n,a,w)
self.grade = g
# Override method of parent class 
def speak(self):
print("%s say : I %d Year old , I'm reading %d grade "%(self.name,self.age,self.grade))
s = student('ken',10,60,3)
s.speak()

The subclass inherits the constructor description of the parent class

If you need the constructor of the parent class in the subclass, you need to explicitly call the constructor of the parent class , Or do not override the constructor of the parent class .

  • Subclasses do not override _init_, When instantiating a subclass , Will automatically call the parent class definition _init_.

  • If I rewrite it **_init_** when , Instantiate subclasses , Will not call the parent class already defined _init_

  • If I rewrite it **_init_** when , To inherit the construction method of the parent class , have access to super Keyword or parent class name , Such as :

    super( Subclass ,self).__init__( Parameters 1, Parameters 2)
    Parent class name .__init__(self, Parameters 1, Parameters 2,...)
    # example 
    class Father(object):
    def __init__(self, name):
    self.name=name
    print ( "name: %s" %( self.name))
    def getName(self):
    return 'Father ' + self.name
    class Son(Father):
    def __init__(self, name):
    super(Son, self).__init__(name)
    print ("hi")
    self.name = name
    def getName(self):
    return 'Son '+self.name
    if __name__=='__main__':
    son=Son('runoob')
    print ( son.getName() )
    

6. Multiple inheritance

Python Equally limited support for multiple inheritance forms . The class definition of multiple inheritance is as follows :

class DerivedClassName(Base1, Base2, Base3):
<statement-1>
.
.
.
<statement-N>

Note the order of the parent classes in parentheses , If the parent class has the same method name , When subclass is used, it does not specify ,python Search from left to right When the method is not found in the subclass , From left to right, find whether the parent class contains methods .

#!/usr/bin/python3
# Class definition 
class people:
# Define basic attributes 
name = ''
age = 0
# Define private properties , Private properties cannot be accessed directly outside the class 
__weight = 0
# Define construction method 
def __init__(self,n,a,w):
self.name = n
self.age = a
self.__weight = w
def speak(self):
print("%s say : I %d year ." %(self.name,self.age))
# Single inheritance example 
class student(people):
grade = ''
def __init__(self,n,a,w,g):
# Call the constructor of the parent class 
people.__init__(self,n,a,w)
self.grade = g
# Override method of parent class 
def speak(self):
print("%s say : I %d Year old , I'm reading %d grade "%(self.name,self.age,self.grade))
# Another class , Preparation for multiple inheritance 
class speaker():
topic = ''
name = ''
def __init__(self,n,t):
self.name = n
self.topic = t
def speak(self):
print(" My name is %s, I'm a speaker , The theme of my speech is %s"%(self.name,self.topic))
# multiple inheritance 
class sample(speaker,student):
a =''
def __init__(self,n,a,w,g,t):
student.__init__(self,n,a,w,g)
speaker.__init__(self,n,t)
test = sample("Tim",25,80,4,"Python")
test.speak() # Same method name , By default, the method of the parent class in brackets is called ( Search from left to right )

The output of the above program is :

 My name is Tim, I'm a speaker , The theme of my speech is Python

7. Method rewriting

If the function of your parent method does not meet your needs , You can override your parent's methods in a subclass , Examples are as follows :

#!/usr/bin/python3
class Parent: # Define parent class 
def myMethod(self):
print (' Call the superclass method ')
class Child(Parent): # Defining subclasses 
def myMethod(self):
print (' Call subclass method ')
c = Child() # Subclass instance 
c.myMethod() # Subclass call override method 
super(Child,c).myMethod() # Call the overridden method of the parent class with the child class object 

super() function Is used to call the parent class ( Superclass ) One way .

8. Class properties and methods

Private properties of class __

__private_attrs Start with two underscores , Declare the property private , Can't be used outside of the class or accessed directly . When used in methods within a class self.__private_attrs.

Class method

Inside the class , Use def Keyword to define a method , Different from general function definition , Class method must contain parameters self, And it's the first parameter ,self Represents an instance of a class .

self The name of is not meant to be dead , You can also use this, But it's best to use as agreed self.

Private method of class

__private_method: Start with two underscores , Declare the method private , Can only be called inside a class , Cannot call... Outside of a class .self.__private_methods.

Examples of private properties of class are as follows :

#!/usr/bin/python3
class JustCounter:
__secretCount = 0 # Private variables 
publicCount = 0 # Open variables 
def count(self):
self.__secretCount += 1
self.publicCount += 1
print (self.__secretCount)
counter = JustCounter()
counter.count()
counter.count()
print (counter.publicCount)
print (counter.__secretCount) # Report errors , Instance cannot access private variables 

Examples of private methods of class are as follows :

#!/usr/bin/python3
class Site:
def __init__(self, name, url):
self.name = name # public
self.__url = url # private
def who(self):
print('name : ', self.name)
print('url : ', self.__url)
def __foo(self): # Private method 
print(' This is the private method ')
def foo(self): # Public methods 
print(' It's the public way ')
self.__foo()
x = Site(' Novice tutorial ', 'www.runoob.com')
x.who() # Normal output 
x.foo() # Normal output 
x.__foo() # Report errors 

Class :

  • _init_ : Constructors , Call... When the object is generated
  • _del_ : Destructor , Use... When releasing objects
  • _repr_ : Print , transformation
  • _setitem_ : Assign values according to the index
  • _getitem_: Get values by index
  • _len_: Get the length
  • _cmp_: Comparison operations
  • _call_: Function call
  • _add_: Add operation
  • _sub_: Subtraction operation
  • _mul_: Multiplication
  • _truediv_: In addition to the operation
  • _mod_: The remainder
  • _pow_: chengfang

Operator overloading

Python Operator overloading is also supported , We can overload the proprietary methods of a class , Examples are as follows :

class Vector:
def __init__(self, a, b):
self.a = a
self.b = b
def __str__(self):
return 'Vector (%d, %d)' % (self.a, self.b)
def __add__(self,other):
return Vector(self.a + other.a, self.b + other.b)
v1 = Vector(2,10)
v2 = Vector(5,-2)
print (v1 + v2)

13、 ... and 、 Namespace and scope

1. Namespace

Namespace (Namespace) It's a mapping from name to object , Most of the namespace is through Python Dictionary to achieve .

Namespaces provide a way to avoid name conflicts in projects . Each namespace is independent , It doesn't matter , Therefore, a namespace cannot have duplicate names , But different namespaces can duplicate names without any effect .

There are generally three namespaces :

  • Built in name (built-in names), Python Language built-in names , Like the function name abs、char And exception name BaseException、Exception wait .
  • Global name (global names), The name defined in the module , Module variables recorded , Include function 、 class 、 Other imported modules 、 Module level variables and constants .
  • Local name (local names), The name defined in the function , The variables of the function are recorded , Including parameters of functions and locally defined variables .( Class is also defined in )

Namespace lookup order :

Suppose we want to use variables runoob, be Python The search order of is : Local namespace -> Global namespace -> Built in namespace .

If the variable is not found runoob, It will discard the search and raise a NameError abnormal :

NameError: name 'runoob' is not defined.

The lifecycle of the namespace :

The lifecycle of a namespace depends on the scope of the object , If the object execution is complete , Then the lifecycle of the namespace ends .

therefore , We cannot access objects with internal namespaces from external namespaces .

# var1 Is the global name 
var1 = 5
def some_func():
# var2 Is a local name 
var2 = 6
def some_inner_func():
# var3 Is the local name of the embedded 
var3 = 7

2. Scope

The scope is a Python The program can directly access the body area of the namespace .

In a python In the program , Direct access to a variable , All scopes will be accessed from the inside out until , Otherwise, an undefined error will be reported .

Python in , Program variables are not accessible anywhere , Access depends on where the variable is assigned .

The scope of a variable determines which part of the program can access which specific variable name .Python There are a total of 4 Kind of , Namely :

There are four scopes :

  • L(Local): The innermost layer , Contains local variables , Like a function / Methods the internal .
  • E(Enclosing): Contains nonlocal (non-local) It's not the whole picture (non-global) The variable of . Like two nested functions , A function ( Or class ) A It contains a function B , So for B For the name of A The scope in is nonlocal.
  • G(Global): The outermost layer of the current script , For example, the global variables of the current module .
  • B(Built-in): Contains built-in variables / Keywords, etc , It was finally searched .

Rule order : L –> E –> G –> B.

I can't find , Then I will go to the part outside the part to find ( Such as closures ), If you can't find it, you will go to the whole situation , And then go to find .

g_count = 0 # Global scope
def outer():
o_count = 1 # In a function other than a closure function
def inner():
i_count = 2 # Local scope

The built-in scope is through a named builtin The standard module of , But the variable name itself is not put into the built-in scope , So you must import this file to use it . stay Python3.0 in , You can use the following code to see which variables are predefined :

>>> import builtins
>>> dir(builtins)

Python There are only modules in (module), class (class) And function (def、lambda) To introduce a new scope , Other code blocks ( Such as if/elif/else/、try/except、for/while etc. ) No new scopes will be introduced , In other words, the variables defined in these statements , It can also be accessed from the outside , The following code :

>>> if True:
... msg = 'I am from Runoob'
...
>>> msg
'I am from Runoob'
>>>

In the example msg Variables are defined in if In the block , But the outside is still accessible .

If you will msg Defined in a function , Then it is a local variable , No access from outside

>>> def test():
... msg_inner = 'I am from Runoob'
...
>>> msg_inner
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'msg_inner' is not defined
>>>

From the wrong information , Illustrates the msg_inner Undefined , Can't use , Because it's a local variable , Can only be used inside a function .

Global and local variables

Variables defined within a function have a local scope , Define a global scope outside the function .

Local variables can only be accessed inside the function they are declared , Global variables can be accessed throughout the program . When you call a function , All variable names declared within the function will be added to the scope . The following example :

#!/usr/bin/python3
total = 0 # This is a global variable 
# Write function description 
def sum( arg1, arg2 ):
# return 2 The sum of parameters ."
total = arg1 + arg2 # total Here is the local variable .; Functions cannot change global variables ??
print (" Function is a local variable : ", total)
return total
# call sum function 
sum( 10, 20 )
print (" Outside the function is the global variable : ", total)

The output of the above example :

 Function is a local variable : 30
Outside the function is the global variable : 0

global and nonlocal keyword

Normal internal scopes cannot change global variables .

When When the internal scope wants to modify the variables of the external scope , You use global and nonlocal keyword 了 .

The following example modifies global variables num:

#!/usr/bin/python3
num = 1
def fun1():
global num # Need to use global Keyword declaration 
print(num)
num = 123
print(num)
fun1()
print(num)

The output of the above example :

1
123
123

If you want to modify the nested scope (enclosing Scope , The outer layer is not a global scope ) The variables in the nonlocal Keyword. , The following example :

#!/usr/bin/python3
def outer():
num = 10
def inner():
nonlocal num # nonlocal Keyword declaration 
num = 100
print(num)
inner()
print(num)
outer()

The output of the above example :

100
100

There is another special case , Suppose the following code is run :

#!/usr/bin/python3
a = 10
def test():
a = a + 1
print(a)
test()

The above procedure shall be executed , The error information is as follows :

Traceback (most recent call last):
File "test.py", line 7, in <module>
test()
File "test.py", line 5, in test
a = a + 1
UnboundLocalError: local variable 'a' referenced before assignment

The error message is local scope reference error , because test Function a Local is used , Undefined , Can't modify .

modify a Is a global variable :

#!/usr/bin/python3
a = 10
def test():
global a
a = a + 1
print(a)
test()

You can also pass... Through function parameters :

#!/usr/bin/python3
a = 10
def test(a):
a = a + 1
print(a)
test(a)

fourteen 、Python3 json Data analysis

JSON (JavaScript Object Notation) Is a lightweight data exchange format .

If you don't already know JSON, You can read our JSON course .

Python3 Can be used in json Module to JSON Data encoding and decoding , It contains two functions :

  • json.dumps(): Code the data .
  • json.loads(): Decode the data .

Python Encoded as JSON Type conversion correspondence table :

PythonJSONdictobjectlist, tuplearraystrstringint, float, int- & float-derived EnumsnumberTruetrueFalsefalseNonenull

1. Encoding and decoding json character string

json.dumps And json.loads example
The following example demonstrates Python The data structure is converted to JSON:

#!/usr/bin/python3
import json
# Python Dictionary type to JSON object 
data = {

'no' : 1,
'name' : 'Runoob',
'url' : 'http://www.runoob.com'
}
json_str = json.dumps(data)
print ("Python Raw data :", repr(data))
print ("JSON object :", json_str)

The result of executing the above code is :

Python Raw data : {'url': 'http://www.runoob.com', 'no': 1, 'name': 'Runoob'}
JSON object : {"url": "http://www.runoob.com", "no": 1, "name": "Runoob"}

The output shows that , Simple types are encoded followed by their original repr() The output is very similar .

Then the above example , We can put a JSON The encoded string is converted back to a Python data structure :

#!/usr/bin/python3
import json
# Python Dictionary type to JSON object 
data1 = {

'no' : 1,
'name' : 'Runoob',
'url' : 'http://www.runoob.com'
}
json_str = json.dumps(data1)
print ("Python Raw data :", repr(data1))
print ("JSON object :", json_str)
# take JSON Object to Python Dictionaries 
data2 = json.loads(json_str)
print ("data2['name']: ", data2['name'])
print ("data2['url']: ", data2['url'])

The result of executing the above code is :

Python Raw data : {'name': 'Runoob', 'no': 1, 'url': 'http://www.runoob.com'}
JSON object : {"name": "Runoob", "no": 1, "url": "http://www.runoob.com"}
data2['name']: Runoob
data2['url']: http://www.runoob.com

2. Encoding and decoding json file

If you're dealing with files instead of strings , You can use json.dump() and json.load() To code and decode JSON data . for example :

# write in JSON data 
with open('data.json', 'w') as f:
json.dump(data, f)
# Reading data 
with open('data.json', 'r') as f:
data = json.load(f)

15、 ... and 、 perform Linux System commands

(1) os.system( Direct calls at the system level )

​ This call is pretty straightforward , And it's synchronous , The program needs to block and wait to return . The return value is system dependent , Return the call return value of the system directly , therefore windows and linux It's different .

Running system commands on only one sub terminal , It can't get the return information after the command is executed

(2) os.popen( New thread mode ), It can be seen that ,popen Methods by p.read() Get terminal output , and popen Need to be closed close(). When the execution is successful ,close() No value returned , When the failure ,close() Return system return value . See how it gets the return value and os.system Different .

This method not only executes the command, but also returns the information object after execution , The advantage is that : Assign the returned result to a variable , Easy to process .

(3) Using modules commands( python3 invalid )

(4) Using modules subprocess(Python Currently, the document fully recommends ), Direct call command , The return value is the system return .shell=True Indicates that the command ends at shell Run in .Python For security reasons in the documentation , Not recommended shell=True.

import subprocess
import os
def subprocess_():
""" subprocess Module execution linux command :return: """
subprocess.call("ls") # perform ls command 
p = subprocess.Popen('ls', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
for line in p.stdout.readlines():
print line,
retval = p.wait()
def system_():
""" system Module execution linux command :return: """
# Use system Module execution linux On command , If the executed command does not return a value res The value of is 256
# If the executed command has a return value and is successfully executed , The return value is 0
res = os.system("ls")
def popen_():
""" popen Module execution linux command . The return value is the class file object , The results are obtained by read() perhaps readlines() :return: """
val = os.popen('ls') # The execution results are contained in val in 
print val.read()
print val.readlines()
def main():
subprocess_() # Method 1
system_() # Method 2
popen_() # Method 3
if __name__ == '__main__':
main()

sixteen 、 Output to log

1. Through the console

A program that takes a long time to run , Or when printing programs with more information , It usually runs programs in the background , Then save the printed information in a file , Check the output log after the program runs . The following commands can be used to complete this function :

nohup python -u stacfile_to_dc.py > test.log 2>&1 &
1
among ,

the last one “&” Indicates the background running program
“nohup” Indicates that the program is not suspended
“python” Indicates execution python Code
“-u” Indicates that caching is not enabled , Print information to log file in real time ( If not -u, The log file will not refresh the code in real time print Function information )
“test.py” Express python Source code file for
“test.log” Represents the output log file
“>” Indicates that the print information is redirected to the log file
“2>&1” Indicates that the standard error output is changed to standard output , You can also output the error information to the log file (0-> stdin, 1->stdout, 2->stderr)
the last one & Indicates the background running program

(1)& command

 function : At the end of an order , This command can be executed in the background

(2)nohup command

 function : Run command without hanging up

2、 View the current background running command

There are two commands you can use ,jobs and ps, The difference is that jobs Used to view the tasks running in the background of the current terminal , If you change the terminal, you can't see it . and ps The command is used to view the dynamics of a transient process , You can see background processes running on other terminals .

(1)jobs command

 function : View the tasks running in the background of the current terminal


​ jobs -l Option to display all tasks of the current terminal PID,jobs The state of can be running,stopped,Terminated.+ The sign indicates the current task ,- The sign indicates the next mission .

(2)ps command

 function : View all current processes

 ps -aux | grep "test.sh" #a: Show all programs u: Display in user oriented format x: Show all programs , Do not differentiate by terminal

2.logging modular

import logging
LOG_FORMAT = "%(asctime)s %(name)s %(levelname)s %(pathname)s %(message)s "# Configure the output log format 
DATE_FORMAT = '%Y-%m-%d %H:%M:%S %a ' # Configure the format of the output time , Pay attention to the months and days to avoid confusion 
logging.basicConfig(level=logging.DEBUG,
format=LOG_FORMAT,
datefmt = DATE_FORMAT ,
filename=r"d:\test\test.log" # With filename Parameters will not be output directly to the console , Instead, write directly to the file 
)
logging.debug("msg1")
logging.info("msg2")
logging.warning("msg3")
logging.error("msg4")
logging.critical("msg5")

logging.basicConfig() The function contains parameter descriptions

Parameter name describe filename Specify the file name of the log output target file ( You can write the file name or the complete absolute path of the file , Write the file name and put the log in the execution file directory , Write the full path and generate log files according to the full path ), After specifying this setting item, the log confidence will not be output to the console filemode Specify the opening mode of the log file , The default is ’a’. It should be noted that , This option should be in filename Only valid when specified format Specifies the log format string , That is, specify the field information contained in the log output and their order .logging The format fields defined by the module are listed below .datefmt Specify Date / Time format . It should be noted that , This option should be in format It contains the time field %(asctime)s Only when effective level Specify the log level of the logger stream Specify the log output target stream, Such as sys.stdout、sys.stderr And the Internet stream. It should be noted that ,stream and filename Can't provide at the same time , Otherwise, it will cause ValueError abnormal stylePython 3.2 The newly added configuration item . Appoint format The style of the format string , It can be taken as ’%’、’{‘ and ’$’, The default is ’%’handlersPython 3.3 The newly added configuration item . If this option is specified , It should be one created multiple Handler The iteratable object of , these handler Will be added to root logger. It should be noted that :filename、stream and handlers Only one of these three configuration items can exist , Not at the same time 2 Or 3 individual , Otherwise, it will cause ValueError abnormal .

logging The defined in the module can be used for format Format string description

Field / The attribute name Use format describe asctime%(asctime)s Construct the time of the log into a readable form , By default ‘2016-02-08 12:00:00,123’ Accurate to milliseconds name%(name)s The name of the logger used , The default is ’root’, Because the default is rootLoggerfilename%(filename)s The file name of the module calling the log output function ; pathname File name section of , Include file suffix funcName%(funcName)s Which is from function Emitted log, Call the function name of the log output function levelname%(levelname)s The final level of the log ( By filter The modified )message%(message)s Log information , Logged text content lineno%(lineno)d The line number of the current log , The line of code that calls the log output function levelno%(levelno)s The log level in digital form of the log record (10, 20, 30, 40, 50)pathname%(pathname)s The full path , The full pathname of the module calling the log output function , There may be no process%(process)s The current process , process ID. There may be no processName%(processName)s Process name ,Python 3.1 newly added thread%(thread)s Current thread , Threads ID. There may be no threadName%(thread)s Thread name module%(module)s The module name that calls the log output function , filename The name part of , File names that do not contain suffixes, that is, file names that do not contain file suffixes created%(created)f current time , use UNIX A standard floating-point representation of time ; When the log event occurred – Time stamp , It's called time.time() Value returned by function relativeCreated%(relativeCreated)d When outputting log information , since Logger Create to Milliseconds from ; Log events occur relative to logging Relative millisecond of module load time msecs%(msecs)d The millisecond part of the event in which the log event occurs .logging.basicConfig() Parameter... Is used in datefmt, Will remove asctime The millisecond part of , You can use this to add

seventeen 、 Multithreading

Multithreading is similar to executing multiple different programs at the same time , Multithreading has the following advantages :

  • Threads can be used to process tasks in programs that take up a long time in the background .
  • User interface can be more attractive , For example, the user clicks a button to trigger the handling of certain events , You can pop up a progress bar to show the progress of processing .
  • Program may run faster .
  • In the implementation of some waiting tasks, such as user input 、 File reading and writing, network receiving and sending data, etc , Threads are more useful . In this case, we can release some precious resources such as memory occupation and so on .

Each independent thread has an entry for the program to run 、 Exit of sequential execution sequence and program . But threads can't execute independently , Must exist in the application , Multiple thread execution control provided by the application .

Each thread has its own set CPU register , Called the context of the thread , This context reflects the CPU The state of the register .

Instruction pointer and stack pointer registers are the two most important registers in the thread context , Threads always run in the context of the process getting , These addresses are used to mark the memory in the address space of the process that owns the thread .

  • Threads can be preempted ( interrupt ).
  • When other threads are running , Threads can be suspended ( Also known as sleep ) – This is the thread's fallback .

Threads can be divided into :

  • ** Kernel thread :** Created and undone by the operating system kernel .
  • ** User threads :** Threads implemented in user programs without kernel support .

Python3 The two modules commonly used in threads are :

  • _thread
  • threading( Recommended )

1、 Thread module

Python3 Through two standard libraries _thread and threading Provides support for threads .

_thread Provides a low level of 、 The original thread and a simple lock , It's compared to threading The function of the module is limited .

threading The module contains _thread Out of all methods in the module , Other methods are also provided :

  • threading.currentThread(): Returns the current thread variable .
  • threading.enumerate(): Returns a thread containing the running thread list. Running after the thread starts 、 Before the end of the , Threads before and after startup are not included .
  • threading.activeCount(): Returns the number of running threads , And len(threading.enumerate()) It has the same result .

In addition to the method of use , The thread module also provides Thread Class to handle threads ,Thread Class provides the following methods :

  • run(): The method used to represent thread activity .
  • start(): Start thread activity .
  • join([time]): Wait until thread aborts . This blocks the calling thread up to the thread's join() Method called to abort - Exit normally or throw unhandled exception - Or optional timeout occurs .
  • isAlive(): Returns whether the thread is active .
  • getName(): Return thread name .
  • setName(): Set the thread name .

(2) Create multithreads through classes

We can do this by directly from threading.Thread Inheritance creates a new subclass , After instantiation, it is called start() Method to start a new thread , That is, it calls the thread's run() Method :

example

#!/usr/bin/python3
import threading
import time
exitFlag = 0
class myThread (threading.Thread):
def __init__(self, threadID, name, counter):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
def run(self):
print (" Start thread :" + self.name)
print_time(self.name, self.counter, 5)
print (" Exit thread :" + self.name)
def print_time(threadName, delay, counter):
while counter:
if exitFlag:
threadName.exit()
time.sleep(delay)
print ("%s: %s" % (threadName, time.ctime(time.time())))
counter -= 1
# Create a new thread 
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)
# Start a new thread 
thread1.start()
thread2.start()
thread1.join()
thread2.join()
print (" Exit main thread ")

The results of the above procedures are as follows ;

 Start thread :Thread-1
Start thread :Thread-2
Thread-1: Wed Apr 6 11:46:46 2016
Thread-1: Wed Apr 6 11:46:47 2016
Thread-2: Wed Apr 6 11:46:47 2016
Thread-1: Wed Apr 6 11:46:48 2016
Thread-1: Wed Apr 6 11:46:49 2016
Thread-2: Wed Apr 6 11:46:49 2016
Thread-1: Wed Apr 6 11:46:50 2016
Exit thread :Thread-1
Thread-2: Wed Apr 6 11:46:51 2016
Thread-2: Wed Apr 6 11:46:53 2016
Thread-2: Wed Apr 6 11:46:55 2016
Exit thread :Thread-2
Exit main thread

(2) Create multithreading through functions

python3 in , Provides a built-in module threading.Thread, You can easily create multithreads ,threading.Thread() General reception 2 Parameters :

  • Thread function name : The function to place the thread to execute in the background , User defined , Mainly do not add ()
  • Parameters of thread function : Parameters required for thread function name , With tuple form Pass in , If you don't need parameters , You don't specify .
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2019-01-23 22:27:22
# @Author : cdl ([email protected])
# @Link : https://github.com/cdlwhm1217096231/python3_spider
# @Version : $Id$
import time
from threading import Thread
# Custom thread function 
def my_threadfunc(name='python3'):
for i in range(2):
print("hello", name)
time.sleep(1)
# Create thread 01, Do not specify parameters 
thread_01 = Thread(target=my_threadfunc)
# Start thread 01
thread_01.start()
# Create thread 02, Specify the parameters , Be careful not to lack commas , Otherwise it's not a tuple
thread_02 = Thread(target=my_threadfunc, args=('Curry',))
# Start thread 02
thread_02.start()

2、 Thread synchronization

If multiple threads modify a data together , Then unexpected results may occur , In order to ensure the correctness of the data , Multiple threads need to be synchronized .

Use Thread Object's Lock and Rlock It can realize simple thread synchronization , Both of these objects have acquire Methods and release Method , For data that requires only one thread at a time , It can be operated in acquire and release Between methods . as follows :

The advantage of multithreading is that it can run multiple tasks at the same time ( At least it feels like this ). But when threads need to share data , There may be data out of sync .

Consider a situation like this : All the elements in a list are 0, Threads "set" Change all elements from back to front to 1, And threads "print" Responsible for reading the list from front to back and printing .

that , Maybe threads "set" At the beginning of the change , Threads "print" So I'm going to print the list , The output is half 0 Half 1, This is the data out of sync . To avoid that , The concept of lock is introduced .

There are two states of lock —— Locked and unlocked . Every time a thread such as "set" To access shared data , Lock must be obtained first ; If there are other threads such as "print" Get locked , So let the thread "set" Pause , That's synchronous blocking ; Wait until the thread "print" Access to complete , After releasing the lock , Let the thread "set" continue .

After such treatment , When printing a list, you can either print it all 0, Or output it all 1, No more half 0 Half 1 The embarrassment of .

example

#!/usr/bin/python3
import threading
import time
class myThread (threading.Thread):
def __init__(self, threadID, name, counter):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
def run(self):
print (" Open thread : " + self.name)
# Get the lock , For thread synchronization 
threadLock.acquire()
print_time(self.name, self.counter, 3)
# Release the lock , Start the next thread 
threadLock.release()
def print_time(threadName, delay, counter):
while counter:
time.sleep(delay)
print ("%s: %s" % (threadName, time.ctime(time.time())))
counter -= 1
threadLock = threading.Lock()
threads = []
# Create a new thread 
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)
# Start a new thread 
thread1.start()
thread2.start()
# Add thread to thread list 
threads.append(thread1)
threads.append(thread2)
# Wait for all threads to finish 
for t in threads:
t.join()
print (" Exit main thread ")

Execute the above procedure , The output is :

 Open thread : Thread-1
Open thread : Thread-2
Thread-1: Wed Apr 6 11:52:57 2016
Thread-1: Wed Apr 6 11:52:58 2016
Thread-1: Wed Apr 6 11:52:59 2016
Thread-2: Wed Apr 6 11:53:01 2016
Thread-2: Wed Apr 6 11:53:03 2016
Thread-2: Wed Apr 6 11:53:05 2016
Exit main thread

3、 Thread priority queue ( Queue)

Python Of Queue Synchronous... Is provided in the module 、 Thread safe queue class , Include FIFO( First in, first out ) queue Queue,LIFO( After the first out ) queue LifoQueue, And priority queues PriorityQueue.

These queues all implement lock primitives , Can be used directly in multithreading , You can use queues to synchronize threads .

queue Introduce

  • queue yes python The standard library of , Commonly known as queue . Can directly import quote , stay python2.x in , The module is called Queue.python3 direct queue that will do
  • stay python in , Data between multiple threads is shared , When multiple threads exchange data , Can't guarantee the security and consistency of data , So when multiple threads need to exchange data , The queue appears , Queues can perfectly solve the data exchange between threads , Ensure the security and consistency of data between threads **( Simply put, multithreading needs to be locked , It is likely to cause deadlock , and queue Self lock . So multithreading queue It will be much better .**

queue Modules have three types of queues and constructors :

  • class queue.Queue(maxsize) #Python queue Modular FIFO First in first out queue .
  • class queue.LifoQueue(maxsize) #LIFO It's like a heap , First in, then out .
  • class queue.PriorityQueue(maxsize) # The lower the priority queue, the higher the priority queue .

Queue Common methods in modules :

  • Queue.qsize() Returns the size of the queue
  • Queue.empty() If the queue is empty , return True, conversely False
  • Queue.full() If the queue is full , return True, conversely False
  • Queue.full And maxsize Size correspondence
  • Queue.get([block[, timeout]]) Get the queue ,timeout Waiting time
  • Queue.get_nowait() Quite a Queue.get(False)
  • Queue.put(item) Written to the queue ,timeout Waiting time
  • Queue.put_nowait(item) Quite a Queue.put(item, False)
  • Queue.task_done() After finishing a job ,Queue.task_done() Function sends a signal to the queue that the task has completed
  • Queue.join() It essentially means waiting until the queue is empty , Do something else

example

#!/usr/bin/python3
import queue
import threading
import time
exitFlag = 0
class myThread (threading.Thread):
def __init__(self, threadID, name, q):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.q = q
def run(self):
print (" Open thread :" + self.name)
process_data(self.name, self.q)
print (" Exit thread :" + self.name)
def process_data(threadName, q):
while not exitFlag:
queueLock.acquire()
if not workQueue.empty():
data = q.get()
queueLock.release()
print ("%s processing %s" % (threadName, data))
else:
queueLock.release()
time.sleep(1)
threadList = ["Thread-1", "Thread-2", "Thread-3"]
nameList = ["One", "Two", "Three", "Four", "Five"]
queueLock = threading.Lock()
workQueue = queue.Queue(10)
threads = []
threadID = 1
# Create a new thread 
for tName in threadList:
thread = myThread(threadID, tName, workQueue)
thread.start()
threads.append(thread)
threadID += 1
# Fill the queue 
queueLock.acquire()
for word in nameList:
workQueue.put(word)
queueLock.release()
# Wait for the queue to clear 
while not workQueue.empty():
pass
# Notify the thread that it's time to exit 
exitFlag = 1
# Wait for all threads to finish 
for t in threads:
t.join()
print (" Exit main thread ")

The results of the above procedures :

 Open thread :Thread-1
Open thread :Thread-2
Open thread :Thread-3
Thread-3 processing One
Thread-1 processing Two
Thread-2 processing Three
Thread-3 processing Four
Thread-1 processing Five
Exit thread :Thread-3
Exit thread :Thread-2
Exit thread :Thread-1
Exit main thread

4. Thread pool

​ Thread pool creates a large number of idle threads at system startup , The program just submits a function to the thread pool , The thread pool will start an idle thread to execute it . When the function is finished , The thread does not die , Instead, it returns to the thread pool again and becomes idle , Wait for the next function to execute .
Besides , Using thread pool can effectively control the number of concurrent threads in the system . When the system contains a large number of concurrent threads , It will lead to a sharp decline in system performance , Even lead to Python Interpreter crashes , The maximum number of threads in the thread pool parameter can control the number of concurrent threads in the system not to exceed this number .

As the notes above say , Thread is good , But too many threads , resources (cpu、 Memory, etc. ) The consumption is also very large ; And the thread is to process a task “ die ” It fell off , It can't be reused , It's a little wasteful

therefore , This “ Thread pool ” This thing appeared . A thread pool is a pool that manages threads , If the capacity of the pool is set , Control the number of threads , This will control the consumption of resources ~

# Thread pool 
# explain :
# 1) A worker can only do one task at a time , But when you finish one task, you can go on to the next task ;
# 2) Multiple tasks can be assigned to a small number of workers , Reduce personnel costs .
# @see https://docs.python.org/zh-cn/3/library/concurrent.futures.html
import threading
from concurrent.futures import ThreadPoolExecutor
# Mission 
def task(taskId):
thread_name = threading.current_thread().getName()
print(' Worker 【%s】 Processing task 【%d】:do something...' % (thread_name, taskId))
def main():
# Initializes the thread pool ( Chamber of Commerce ), Define the maximum number of workers in the pool 
pool = ThreadPoolExecutor(max_workers=5, thread_name_prefix='Thread')
# Get ready 10 A mission 
for i in range(10):
# Submit task to pool ( Chamber of Commerce ) in ( It is automatically assigned to workers )
pool.submit(task, i+1)
if __name__ == '__main__':
main()

The example here is the same as above , Just add a bit of code to simulate the time-consuming task , It is convenient for you to observe how the thread pool allocates tasks

# Thread pool 
# explain :
# 1) A worker can only do one task at a time , But when you finish one task, you can go on to the next task ;
# 2) Multiple tasks can be assigned to a small number of workers , Reduce personnel costs .
# 3) Tasks are assigned to idle workers in sequence , But each task takes a different amount of time , Tasks are not completed in sequence , Tasks submitted later may be completed first 
import time
import random
import threading
from concurrent.futures import ThreadPoolExecutor
# Mission 
def task(taskId, consuming):
thread_name = threading.current_thread().getName()
print(' Worker 【%s】 Processing task 【%d】:do something...' % (thread_name, taskId))
# The simulation task takes time ( second )
time.sleep(consuming)
print(' Mission 【%d】:done' % taskId)
def main():
# 5 One worker 
pool = ThreadPoolExecutor(max_workers=5, thread_name_prefix='Thread')
# Get ready 10 A mission 
for i in range(10):
# The simulation task takes time ( second )
consuming = random.randint(1, 5)
pool.submit(task, i+1, consuming)
if __name__ == '__main__':
main()

eighteen 、 modular

To write maintainable code , We group a lot of functions , Put them in separate files , such , Each file contains relatively little code , Many programming languages use this way of organizing code . stay Python in , One .py File is called a module (Module).

You may think of , What if different people write the same module name ? To avoid module name conflicts ,Python It also introduces the method of organizing modules by directory , Called a package (Package).

for instance , One abc.py It's a file called abc Module , One xyz.py It's a file called xyz Module .

Now? , Suppose our abc and xyz These two module names conflict with other modules , So we can organize modules through packages , To avoid conflict . The way to do this is to choose a top-level package name , such as mycompany, Store in accordance with the following directory :

mycompany
├─ __init__.py
├─ abc.py
└─ xyz.py

After introducing the package , As long as the top-level package name does not conflict with others , Then all modules will not conflict with others . Now? ,abc.py The name of the module becomes mycompany.abc, Allied ,xyz.py The module name of has changed to mycompany.xyz.

Please note that , There will be one under each package directory __init__.py The file of , This file must exist , otherwise ,Python Just think of this directory as a normal Directory , Not a bag .__init__.py It can be an empty file , There can be Python Code , because __init__.py It's a module in itself , And its module name is mycompany.

Allied , There can be multiple directories , The package structure of multi-level structure . For example, the following directory structure :

mycompany
├─ web
│ ├─ __init__.py
│ ├─ utils.py
│ └─ www.py
├─ __init__.py
├─ abc.py
└─ utils.py

file www.py The module name of is mycompany.web.www, Two documents utils.py The module names of are mycompany.utils and mycompany.web.utils.

When you create your own modules , it is to be noted that :

  • Module name should follow Python Variable naming conventions , Don't use Chinese 、 Special characters ;
  • Do not conflict module name with system module name , It is better to check whether the module already exists in the system , The method of examination is Python Interactive environment execution import abc, If successful, the system has this module .

Using modules

Python There are many very useful modules built in , As long as the installation is complete , These modules can be used immediately .

We built in sys Module as an example , Write a hello Module :

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
' a test module '
__author__ = 'Michael Liao'
import sys
def test():
args = sys.argv
if len(args)==1:
print('Hello, world!')
elif len(args)==2:
print('Hello, %s!' % args[1])
else:
print('Too many arguments!')
if __name__=='__main__':
test()

The first 1 Xing He 2 Line is standard comment , The first 1 Line comments can make this hello.py The document is directly in Unix/Linux/Mac Up operation , The first 2 Line comments indicate .py The document itself uses the standard UTF-8 code ;

The first 4 Line is a string , Document comments representing the module , The first string of any module code is treated as a document comment for the module ;

The first 6 Line usage __author__ Variables write the author in , In this way, when you open the source code, others can look up to your name ;

That's all Python Module standard file template , Of course, you can delete all of them , however , It must be right to do things according to the standard .

And then there's the real code part .

Last , Notice these two lines of code :

if __name__=='__main__':
test()

When we Run on the command line hello Module file ,Python The interpreter takes a special variable __name__ Set as __main__, And if Import this... Elsewhere hello modular when ,if Judgment will fail , therefore , such if Testing allows a module to execute some extra code through the command line runtime , The most common is running tests .

We can run... On the command line hello.py Look at the effect :

$ python3 hello.py
Hello, world!
$ python hello.py Michael
Hello, Michael!

If you start Python Interactive environment , Then import hello modular :

$ python3
Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 23 2015, 02:52:03)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import hello
>>>

Import time , No printing Hello, word!, Because no execution test() function .

call hello.test() when , To print out Hello, word!

>>> hello.test()
Hello, world!

Scope

In a module , We may define many functions and variables , But some functions and variables we want to use for others , Some functions and variables we want to use only inside the module . stay Python in , It's through _ Prefix to achieve .

Normal function and variable names are public (public), Can be quoted directly , such as :abc,x123,PI etc. ;

similar __xxx__ Such variables are special variables , Can be quoted directly , But there are special uses , Like the one above __author__,__name__ It's a special variable ,hello Module defined document annotations can also use special variables __doc__ visit , We don't use this variable name for our own variables ;

similar _xxx and __xxx Such functions or variables are not public (private), Should not be quoted directly , such as _abc,__abc etc. ;

The reason why we say ,private Functions and variables “ Should not be ” Be quoted directly , instead of “ You can't ” Be quoted directly , Because Python There is no way to completely restrict access private Function or variable , however , You should not refer to private Function or variable .

private Functions or variables should not be referenced , What's the use of them ? Please see the example :

def _private_1(name):
return 'Hello, %s' % name
def _private_2(name):
return 'Hi, %s' % name
def greeting(name):
if len(name) > 3:
return _private_1(name)
else:
return _private_2(name)

We make it public in the module greeting() function , And use the internal logic private Functions are hidden , such , call greeting() Functions don't have to worry about the internal private Function details , It's also a very useful way to encapsulate and abstract code , namely :

External functions that do not need to be referenced are all defined as private, Only functions that need to be referenced externally are defined as public.

nineteen 、 Type and check the parameters and return values of the function

python Type and check the parameters and return values of the function _sgyuanshi The blog of -CSDN Blog _python Declare the function return type

python It has never been the mainstream language for developing big projects , Whether it's the front end or the back end , The main reasons are the following :

  • python It's an explanatory language , Operating efficiency ratio java Such language is slow ;
  • python It's dynamic language , The cost of later maintenance is very high , The important thing is that there is no type check , Of course, it also includes that new variables do not need to be declared and specified types, etc .

however , stay python3.5 after , It adds the type assignment and check of function parameters and return values , And when creating a new variable, you can also specify the type .

The basic type specifies

for example , The following function test, Input parameters are specified a by int type , and b by str type , And the return value is srt type . You can see ,
In the method , We finally returned to a int, here pycharm There will be a warning ;
When we call this method , Parameters a We're entering a string , There will also be warnings ;
But it's very important that ,pycharm It's just a warning , But in fact, the operation will not report an error , After all python The essence of language is dynamic language

More complex assignments

In addition to the above basic data type specification , You can also specify collection related types .

from typing import List
Vector = List[float]
def scale(scalar: float, vector: Vector) -> Vector:
return [scalar * num for num in vector]
# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
from typing import Dict, Tuple, Sequence
ConnectionOptions = Dict[str, str]
Address = Tuple[str, int]
Server = Tuple[Address, ConnectionOptions]
def broadcast_message(message: str, servers: Sequence[Server]) -> None:
...
# The static type checker will treat the previous type signature as
# being exactly equivalent to this one.
def broadcast_message(
message: str,
servers: Sequence[Tuple[Tuple[str, int], Dict[str, str]]]) -> None:
...

Here we need to pay attention to , Tuple is a special type , Because it's immutable . therefore , When we specify Tuple[str, str] when , You can only pass in a length of 2, And all the elements in the tuple are str type

Specify a generic type

from typing import Sequence, TypeVar, Union
T = TypeVar('T') # Declare type variable
def first(l: Sequence[T]) -> T: # Generic function
return l[0]
T = TypeVar('T') # Can be anything
A = TypeVar('A', str, bytes) # Must be str or bytes
A = Union[str, None] # Must be str or None

Type assignment when creating variables

from typing import NamedTuple
class Employee(NamedTuple):
name: str
id: int = 3
employee = Employee('Guido')
assert employee.id == 3

More personalized assignments

I listed these above , Basically, it can meet most of our needs , If you want to know more , You can go to python Official website , It has a very detailed introduction .

twenty 、 Annotation specifications

Python Style standard — Google Open source project style guide (zh-google-styleguide.readthedocs.io)

1. modular

Each file should contain a license template . According to the license to use the project ( for example , Apache 2.0, BSD, LGPL, GPL), Choose the right pattern . It should begin with a description of the module content and usage .

"""A one line summary of the module or program, terminated by a period. Leave one blank line. The rest of this docstring should contain an overall description of the module or program. Optionally, it may also contain a brief description of exported classes and functions and/or usage examples. Typical usage example: foo = ClassFoo() bar = foo.FunctionBar() """

2. Class annotation specification

Class should have a document string under its definition that describes the class . If your class has public properties (Attributes), Then there should be an attribute in the document (Attributes) paragraph . And it should follow the same format as function parameters .

class SampleClass(object):
"""Summary of class here. Longer class information.... Longer class information.... Attributes: likes_spam: A boolean indicating if we like SPAM or not. eggs: An integer count of the eggs we have laid. """
def __init__(self, likes_spam=False):
"""Inits SampleClass with blah."""
self.likes_spam = likes_spam
self.eggs = 0
def public_method(self):
"""Performs operation blah."""

3. Functions and methods

The document string should contain what functions do , And a detailed description of the inputs and outputs . Usually , It should not be described ” How do you do it? ”, Unless it's a complex algorithm . There should be enough information in the string , When someone else writes code to call the function , He doesn't need to look at a line of code , Just look at the document string . For complex code , It makes more sense to annotate code than to use document strings . Subclass methods that override the base class should have a similar See base class Simple comments to guide the reader to the document comments of the base class methods . If overloaded subclass methods are very different from base class methods , Then the note should indicate this information .

Several aspects of the function should be described in specific sections , These aspects are described below . Each section should start with a heading line . The title line ends with a colon . Except for the title line , The rest of the section should be indented 2 A space .

Args:
List the name of each parameter , And use a colon and a space after the name , Separate the description of the parameter . If the description is too long than a single line 80 character , Use 2 perhaps 4 Hanging indent of spaces ( Consistent with the rest of the document ). The description should include the type and meaning required . If a function accepts *foo( Variable length parameter list ) perhaps **bar ( Any key parameter ), It should be listed in detail *foo and **bar.
Returns: ( perhaps Yields: For generators )
Describes the type and semantics of the return value . If the function returns None, This part can be omitted .
Raises:
List all exceptions related to the interface .
def fetch_smalltable_rows(table_handle: smalltable.Table,
keys: Sequence[Union[bytes, str]],
require_all_keys: bool = False,
) -> Mapping[bytes, Tuple[str]]:
"""Fetches rows from a Smalltable. Retrieves rows pertaining to the given keys from the Table instance represented by table_handle. String keys will be UTF-8 encoded. Args: table_handle: An open smalltable.Table instance. keys: A sequence of strings representing the key of each table row to fetch. String keys will be UTF-8 encoded. require_all_keys: Optional; If require_all_keys is True only rows with values set for all keys will be returned. Returns: A dict mapping keys to the corresponding table row data fetched. Each row is represented as a tuple of strings. For example: {b'Serak': ('Rigel VII', 'Preparer'), b'Zim': ('Irk', 'Invader'), b'Lrrr': ('Omicron Persei 8', 'Emperor')} Returned keys are always bytes. If a key from the keys argument is missing from the dictionary, then that row was not found in the table (and require_all_keys must have been False). Raises: IOError: An error occurred accessing the smalltable. """

4. Block and line comments

What needs to be commented most is the technical part of the code . If you're next time Code review You have to explain , So you should annotate it now . For complex operations , A few lines of comments should be written before the operation begins . For code that is not clear at a glance , A comment should be added at the end of the line .

# We use a weighted dictionary search to find out where i is in
# the array. We extrapolate position based on the largest num
# in the array and the array size and then do binary search to
# get the exact number.
if i & (i-1) == 0: # True if i is 0 or a power of 2.

To improve readability , Comments should at least leave the code 2 A space .

5. name

How to write the module name : module_name ; How to write the package name : package_name ; Class name : ClassName ; Method name : method_name ; Exception names : ExceptionName ; Function name : function_name ; Global constant name : GLOBAL_CONSTANT_NAME ; Global variable name : global_var_name ; Instance name : instance_var_name ; Function parameter name : function_parameter_name ; Local variable name : local_var_name . Function name , Variable and file names should be descriptive , Try to avoid abbreviations , In particular, avoid using abbreviations that are unclear and difficult to understand by non project personnel , Don't abbreviate by deleting letters from words . Always use a .py As a file suffix , Don't use dashes .

Names that should be avoided

  1. Single character name , Except for counters and iterators , As try/except Exception declared in e, As with Statement f.
  2. package / Hyphens in module names (-)
  3. Names that start and end with double underscores (Python Retain , for example ___init_)

Naming conventions

  1. So-called ” Inside (Internal)” Indicates only available within the module , perhaps , Protected or private within a class .
  2. use Underline (_) start Indicates that the module variable or function is **protected( Protect )** Of ( Use from module import * It doesn't contain ).
  3. use Double underline (__) start An instance variable or method of represents an in class private .
  4. Put related classes and top-level functions in the same module . Unlike Java, There's no need to limit a class to a module .
  5. Use capital letters for class names ( Such as CapWords, namely Pascal style ), But the module name should be lowercase and underlined ( Such as lower_with_under.py). Although there are many existing modules that use something like CapWords.py Such a name , But now it's not encouraged , Because if the module name happens to be the same as the class name , It can be confusing .

file name

all python All script files should start with .py Is a suffix and does not contain -. If you need an executable without a suffix , You can use soft joins or include exec "$0.py" "[email protected]" Of bash Script .

Python The father of Guido Recommended specifications

TypePublicInternalModuleslower_with_under_lower_with_underPackageslower_with_underClassesCapWords_CapWordsExceptionsCapWordsFunctionslower_with_under()_lower_with_under()Global/Class ConstantsCAPS_WITH_UNDER_CAPS_WITH_UNDERGlobal/Class Variableslower_with_under_lower_with_underInstance Variableslower_with_under_lower_with_under (protected) or __lower_with_under (private)Method Nameslower_with_under()_lower_with_under() (protected) or __lower_with_under() (private)Function/Method Parameterslower_with_underLocal Variableslower_with_under

6.Main

Even a file intended to be used as a script , Should also be Importable Of . And a simple import should not lead to the main function of the script (main functionality) Be performed , It's a side effect . The main function should be placed in a main() function in .

stay Python in , pydoc And unit testing requires that modules must be importable . Your code should always check before executing the main program if __name__ == '__main__' , In this way, when the module is imported, the main program will not be executed .

Must let Python Interpreter knows , Current level code to run , Is the module file itself , Or other programs that import modules .

To achieve this , You need to use Python Built in system variables name, It is used to identify the module name of the module .

therefore ,if __name__ == '__main__': The role of is to ensure that only Run the module separately when , This expression holds , You can enter this judgment grammar , Execute the test code ; conversely , If it's just Import to other program files as modules in , Then this expression will not hold , It will only execute according to the syntax of the import module .

  • Perform the procedure separately ,python test.py

    Will enter judgment , Execute internal statements ; At this time, it is used as the entrance of the main program

  • Import other programs as modules ,import test------test.totest()

    Will not enter into judgment , Execute only the methods specified by the imported module

# file name app.py
def run(argv):
def main():
run()
# process non-flag arguments
if __name__ == '__main__':
main()

Execute at this time python app.py, Will enter app.py The judgment of the , One after another main() run() function

# file name test.py
import app
def main():
app.run("abc")
...
if __name__ == '__main__':
main()

Execute at this time test.py, Will not enter the app.py The judgment of the , Only the imported method will be used run() function

All the top-level code is executed when the module is imported . Be careful not to call functions , Create objects , Or implement those that shouldn't be in use pydoc What to do when .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved