Appoint python Interpreter and encoding method
#!/usr/bin/python
# -*- coding: UTF-8 -*-
Unicode
Is a human readable character format ;ASCII
、UTF-8
、GBK
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 -*-
stay Python 3 in , You can use Chinese as the variable name , Not ASCII Identifiers are also allowed .
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']
Appoint Python Interpreter
#!/usr/bin/python3
# Single-line comments
print ("Hello, Python!") # The second note
''' The third note Fourth note '''
""" Fifth note Sixth note """
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
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']
python There are four types of middle numbers : Integers 、 Boolean type 、 Floating point and complex number .
#!/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
The following program will wait for user input after pressing enter :
#!/usr/bin/python3
input("\n\n Press down enter Key to exit .")
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')
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()
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
$ python test.py arg1 arg2 arg3
(1)Python It can also be used in sys Of sys.argv To get command line arguments :
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 :
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:
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 .
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.
Python3 There are six standard data types in :
Python3 Of the six standard data types :
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 :
** 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
\>>> 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 :
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 :
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 :
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)
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 :
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
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 :
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'])
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'])
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
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 .
if condition_1:
statement_block_1
elif condition_2:
statement_block_2
else:
statement_block_3
Python of use elif Instead of else if, therefore if The keyword of the statement is :if – elif – else.
Be careful :
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
while Judge the condition (condition):
Execute statement (statements)……
Also notice colons and indents . in addition , stay Python There is no do…while loop .
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).
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!")
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 !")
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 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 .
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!")
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()
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)
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()
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 .
You can define a function that you want to function , Here are the simple rules :
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 .
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 ")
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 .
stay python in ,strings, tuples, and numbers Is an object that cannot be changed , and list,dict And so on are modifiable objects .
python Parameter passing of function :
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 .
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.
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
Here are the formal parameter types that can be used when calling a function :
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()
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 ")
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" )
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
>>>
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 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 ))
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)
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
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 .
Here are Python Methods in the list :
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]
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]
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 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]
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]]
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
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 ).
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'}
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}
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
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')
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
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 .
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 .
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 .
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 .
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']
>>>
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 :
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 .
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 .
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 .
>>> 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'
>>> 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 .
(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.
^<> 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
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
print('{:.2f}'.format(3.14159))
result :3.14
Keep two decimal places , Round the last two digits
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
% 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().
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)
open() Will return a file object , The basic syntax is as follows :
open(filename, mode)
Open the full list of files in different modes :
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()
The remaining examples in this section assume that you have created a named f The file object of .
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() 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() 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)
#!/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(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() Returns the current location of the file object , It is the number of bytes from the beginning of the file .
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 :
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'
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 .
import pickle
python Of pickle The module implements the basic data sequence and deserialization .
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()
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 Object use open Function to create , The following table lists them file Functions commonly used by objects :
import os
os Module provides a very rich way to handle files and directories . The common methods are shown in the following table :
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 .
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 .
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 .
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 ;
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 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 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 .')
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
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 .
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'
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 .
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 "
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 .
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 .
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 .
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
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()
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 .
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()
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() )
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
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 .
__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.
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: 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
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)
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 :
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
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 :
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 .
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
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)
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 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
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)
(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()
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
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")
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 .Multithreading is similar to executing multiple different programs at the same time , Multithreading has the following advantages :
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 divided into :
Python3 The two modules commonly used in threads are :
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 :
In addition to the method of use , The thread module also provides Thread Class to handle threads ,Thread Class provides the following methods :
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
python3 in , Provides a built-in module threading.Thread, You can easily create multithreads ,threading.Thread() General reception 2 Parameters :
#!/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()
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
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 .
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
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()
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 .
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!
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.
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 :
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 .
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
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
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
from typing import NamedTuple
class Employee(NamedTuple):
name: str
id: int = 3
employee = Employee('Guido')
assert employee.id == 3
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 .
Python Style standard — Google Open source project style guide (zh-google-styleguide.readthedocs.io)
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() """
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."""
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. """
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 .
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
- Single character name , Except for counters and iterators , As
try/except
Exception declared ine
, Aswith
Statementf
.- package / Hyphens in module names (-)
- Names that start and end with double underscores (Python Retain , for example ___init_)
Naming conventions
- So-called ” Inside (Internal)” Indicates only available within the module , perhaps , Protected or private within a class .
- use Underline (_) start Indicates that the module variable or function is **protected( Protect )** Of ( Use from module import * It doesn't contain ).
- use Double underline (__) start An instance variable or method of represents an in class private .
- Put related classes and top-level functions in the same module . Unlike Java, There's no need to limit a class to a module .
- 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 includeexec "$0.py" "[email protected]"
Of bash Script .
Python The father of Guido Recommended specifications
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 .