brief introduction
The content is long, suitable for collection and learning. This content contains all knowledge points and grammar. Friends who like it can collect it for future learning.
Python is a high-level scripting language that combines interpretability, compilation, interactivity and object-oriented. Python was invented by Guido van Rossum at the National Institute of mathematics and computer science in the Netherlands at the end of 1989. The first public release was released in 1991.
characteristic
-
Easy to learn: Python has relatively few keywords, simple structure, and a clearly defined syntax, which is easier to learn.
-
Easy to read: Python code is more clearly defined.
-
Easy to maintain: Python's success is that its source code is quite easy to maintain.
-
An extensive standard library: one of Python's biggest advantages is its rich library, cross platform, and good compatibility in UNIX, Windows and macOS.
-
Interactive mode: with the support of interactive mode, you can input the language of executing code and obtaining results from the terminal, interactive testing and debugging code fragments.
-
Portability: Python has been ported (that is, made to work) to many platforms based on its open source features.
-
Extensible: if you need a fast running key code, or you want to write some algorithms that do not want to be open, you can use C or C++ to complete that part of the program and then call it from your Python program.
-
Database: Python provides interfaces to all major commercial databases.
-
GUI Programming: Python supports GUI, which can be created and ported to many system calls.
-
Embeddable: you can embed Python into C/C + + programs to give users of your programs the ability to "script".
-
Object oriented: Python is a strong object-oriented language. Any content in a program is collectively referred to as an object, including numbers, strings, functions, etc.
Basic grammar
Run Python
Interactive interpreter
After executing Python in the command line window, enter the interactive interpreter of Python. exit() or Ctrl + D to exit the interactive interpreter.
Command line script
In the command line window, execute Python script file Py to execute Python script files.
Specify interpreter
If you enter #/ usr/bin/env python, you can execute / path / to / script file in the command line window Py to execute the script file.
Note: this method does not support Windows environment.
code
By default, 3 X source files are UTF-8 encoded, and strings are Unicode characters. You can also manually specify the file encoding:
# -*- coding: utf-8 -*-
perhaps
# encoding: utf-8
Note: this line label must be on the first line of the file
identifier
-
The first character must be an English letter or underscore_ .
-
The rest of the identifier consists of letters, numbers, and underscores.
-
Identifiers are case sensitive.
Note: from 3 Starting with X, non ASCII identifiers are also allowed, but not recommended.
Reserved word
Reserved words are keywords and we cannot use them as any identifier name. Python's standard library provides a keyword module that 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']
notes
Single line annotation adopts #, and multi line annotation adopts' 'or' '.
# This is a single line comment ''' This is a multiline comment This is a multiline comment ''' """ This is also a multiline comment This is also a multiline comment """
Lines and indents
Python's most distinctive feature is that it uses indentation to represent code blocks without curly braces {}. The number of indented spaces is variable, but statements in the same code block must contain the same number of indented spaces. Inconsistent indentation will lead to running errors.
Multiline statement
Python usually writes a statement on one line, but if the statement is very long, we can use backslash \ to implement multi line statements.
total = item_one + \ item_two + \ item_three
A backslash is not required for multiline statements in [], {}, or ().
Blank line
Empty lines are used to separate functions or class methods, indicating the beginning of a new piece of code. The class and function entry are also separated by an empty line to highlight the beginning of the function entry.
Blank lines, unlike code indentation, are not part of Python syntax. When writing, do not insert blank lines, and the Python interpreter will run without error. However, the function of blank lines is to separate two sections of code with different functions or meanings, so as to facilitate the maintenance or reconstruction of the code in the future.
Remember: blank lines are also part of the program code.
Waiting for user input
The input function can wait and receive user input from the command line.
content = input("\n\n Please enter something and press Enter key\n") print(content)
Write multiple statements on the same line
Python can use multiple statements in the same line, and semicolons are used between statements; division.
import sys; x = 'hello world'; sys.stdout.write(x + '\n')
Multiple statements form a code group
Indenting the same set of statements constitutes a code block, which we call a code group.
For compound statements such as if, while, def and class, the first line starts with keywords and ends with colon:, and one or more lines of code after this line form a code group.
We call the first line and the following code group a clause.
print output
The default output of print is newline. If you want to realize no newline, you need to add end = "" or other non newline character string at the end of the variable:
print('123') # Default Wrap print('123', end = "") # nowrap
import and from
In Python, use "import" or "from Import , to import the corresponding module.
Import the whole module in the format of import module_name
Import a function from a module in the form of from module_name import func1
Import multiple functions from a module in the form of from module_name import func1, func2, func3
Import all functions in a module in the form of from module_name import *
operator
Arithmetic operator
operator | describe |
---|---|
+ | plus |
- | reduce |
* | ride |
/ | except |
% | Take mold |
** | power |
// | Take and divide |
Comparison operator
operator | describe |
---|---|
== | be equal to |
!= | Not equal to |
> | greater than |
< | less than |
>= | Greater than or equal to |
<= | Less than or equal to |
Assignment Operators
operator | describe |
---|---|
= | Simple assignment operator |
+= | Additive assignment operator |
-= | Subtraction assignment operator |
*= | Multiplication assignment operator |
/= | Division assignment operator |
%= | Modulo assignment operator |
**= | Power assignment operator |
//= | Integer division assignment operator |
Bitwise Operators
Logical operator
member operator
Identity operator
Operator priority
Operators with the same priority will proceed from left to right. You can change the order of operations with parentheses ().
variable
The variable must be "defined" (i.e. given a value) before use, otherwise an error will be reported:
>>> name Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'name' is not defined
data type
Boolean
Only two values, True and False, indicate True or False.
Number
Integer (int)
Integer value, either positive or plural, without decimal. The 3.x integer has no size limit and can be used as a long type, so 3 X No 2 Long type of X.
Floating point
Floating point type consists of integer part and decimal part. Floating point type can also be represented by scientific counting method (2.5e2 = 2.5 x 10^2 = 250)
Complex
The complex number is composed of real part and imaginary part, which can be represented by a + bj or complex(a,b). Both the real part a and imaginary part B of the complex number are floating point.
Digital operation
-
When different types of numbers are mixed, integers are converted to floating-point numbers
-
The results of floating-point operations may be different on different machines
-
In integer division, division / always returns a floating-point number. If you only want to get the result of an integer and discard the possible fraction, you can use the operator / /.
-
//The number obtained is not necessarily of integer type, but is related to the data type of denominator numerator
-
In interactive mode, the last output expression result is assigned to the variable_ Is a read-only variable
Mathematical function
Note: to use the following functions, you need to import the math package first.
Random number function
Note: to use the following functions, you need to import the random package first.
trigonometric function
Note: to use the following functions, you need to import the math package first.
Mathematical Constants
String (string)
-
Single quotation marks and double quotation marks are used exactly the same
-
Use three quotation marks ('' 'or' ') to specify a multiline string
-
The escape character (backslash \) can be used to escape. Using r can prevent the backslash from escaping. For example, r"this is a line with \n", it will be displayed instead of line feed
-
Concatenate strings literally, such as "this" "is" "string" will be automatically converted to this is string
-
Strings can be concatenated with the + operator and repeated with the * operator
-
Strings can be indexed in two ways, starting with 0 from left to right and - 1 from right to left
-
The string cannot be changed
-
There is no separate character type. A character is a string of length 1
-
The syntax format of string interception is as follows: variable [header subscript: tail subscript]
Escape character
String operator
String formatting
In Python, string formatting is not the sprintf function, but the% symbol. For example:
print("My name is%s, this year %d Years old!" % ('Xiao Ming', 10)) // Output: My name is Xiao Ming. I'm 10 years old!
Format symbol:
Auxiliary instructions:
Starting from Python 2.6, a new string formatting function, {str.format(), has been added, which enhances the function of string formatting.
Multiline string
-
Wrap the string contents in three quotation marks ('' 'or' ')
-
The multi line string content supports escape characters, and the usage is the same as that of single and double quotation marks
-
The contents wrapped in three quotation marks include variable reception or operation, that is, string, otherwise it is multi line comment
example:
string = ''' print(\tmath.fabs(-10)) print(\nrandom.choice(li)) ''' print(string)
Output:
print( math.fabs(-10)) print( random.choice(li))
Unicode
In 2 In X, ordinary strings are stored in 8-bit ASCII code, while Unicode strings are stored as 16 bit Unicode strings, which can represent more character sets. The syntax used is to prefix the string with {u.
In 3 In X, all strings are Unicode strings.
String function
Bytes
In 3 In X, strings and binary data are completely distinguished. Text is always Unicode, represented by str type, and binary data is represented by bytes type. Python 3 will not mix str and bytes in any implicit way. You cannot splice strings and byte streams, search strings in byte streams (and vice versa), or pass strings into functions whose parameters are byte streams (and vice versa).
-
The byte type is different from the str type, and their methods are only encode() and decode().
-
For byte type data, add a 'B' before the conventional str type to distinguish it, for example, 'b'abc'.
-
Only when it is necessary to encode str into bytes, such as transmitting data through the network; Or when we need to decode bytes into str, we will pay attention to the difference between str and bytes.
bytes to str:
b'abc'.decode() str(b'abc') str(b'abc', encoding='utf-8')
str to bytes:
'China'.encode() bytes('China', encoding='utf-8')
List
-
A list is an unordered and repeatable data sequence in which elements can be added and deleted at any time.
-
Each element of the list page is assigned a numeric index, starting at 0
-
The list is created with square brackets and the elements are separated by commas
-
List element values can be of any type, including variables
-
Use square brackets to access, slice, modify, delete and other operations on the list. The open and close interval is in the form of [)
-
The element access of the list can be nested
-
Any expression can be in square brackets
Create list
hello = (1, 2, 3) li = [1, "2", [3, 'a'], (1, 3), hello]
Access element
li = [1, "2", [3, 'a'], (1, 3)] print(li[3]) # (1, 3) print(li[-2]) # [3, 'a']
Slice access
Format: list_name[begin:end:step] begin indicates the start position (0 by default), end indicates the end position (the last element by default), and step indicates the step size (1 by default)
hello = (1, 2, 3) li = [1, "2", [3, 'a'], (1, 3), hello] print(li) # [1, '2', [3, 'a'], (1, 3), (1, 2, 3)] print(li[1:2]) # ['2'] print(li[:2]) # [1, '2'] print(li[:]) # [1, '2', [3, 'a'], (1, 3), (1, 2, 3)] print(li[2:]) # [[3, 'a'], (1, 3), (1, 2, 3)] print(li[1:-1:2]) # ['2', (1, 3)]
To access the elements of an embedded list:
li = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ['a', 'b', 'c']] print(li[1:-1:2][1:3]) # (3, 5) print(li[-1][1:3]) # ['b', 'c'] print(li[-1][1]) # b
Modify list
By using square brackets, you can flexibly modify, replace and delete the elements of the list.
li = [0, 1, 2, 3, 4, 5] li[len(li) - 2] = 22 # Modify [0, 1, 2, 22, 4, 5] li[3] = 33 # Modify [0, 1, 2, 33, 4, 5] li[1:-1] = [9, 9] # Replace [0, 9, 9, 5] li[1:-1] = [] # Delete [0, 5]
Delete element
You can use the del statement to delete a specified range of elements in a list.
li = [0, 1, 2, 3, 4, 5] del li[3] # [0, 1, 2, 4, 5] del li[2:-1] # [0, 1, 5]
List operator
-
+Used to merge lists
-
*Used to repeat list elements
-
In is used to determine whether the element exists in the list
-
for ... in ... Used to traverse list elements
[1, 2, 3] + [3, 4, 5] # [1, 2, 3, 3, 4, 5] [1, 2, 3] * 2 # [1, 2, 3, 1, 2, 3] 3 in [1, 2, 3] # True for x in [1, 2, 3]: print(x) # 1 2 3
List function
-
len(list) number of list elements
-
max(list) the maximum value in the list element
-
min(list) the minimum value in the list element
-
list(seq) converts tuples to lists
li = [0, 1, 5] max(li) # 5 len(li) # 3
Note: use the max/min function for the list, 2 There is no requirement for element value type in X, 3 X requires that the element value types must be consistent.
List method
-
list.append(obj)
Add a new object at the end of the list
-
list.count(obj)
Returns the number of times an element appears in the list
-
list.extend(seq)
Append multiple values from another sequence at the end of the list at once
-
list.index(obj)
Returns the index position of the lookup object. If the object is not found, an exception is thrown
-
list.insert(index, obj)
Inserts the specified object into the list at the specified location
-
list.pop([index=-1]])
Removes an element from the list (the default last element) and returns the value of that element
-
list.remove(obj)
Removes the first occurrence of a value in the list
-
list.reverse()
Reverses the elements of the list
-
list.sort(cmp=None, key=None, reverse=False)
Sort the original list. If parameters are specified, the comparison function specified by the comparison function is used
-
list.clear()
You can also clear the list by using del list [:], li = []
-
list.copy()
The copy list is assigned to another variable by using the equal sign by default. In fact, it refers to the list variable. If you want to achieve
List derivation
List derivation provides an easy way to create a list from a sequence. Usually, applications apply some operations to each element of a sequence, use the results obtained as the elements to generate a new list, or create subsequences according to the determined decision conditions.
Each list derivation is followed by an expression after for, followed by zero to more for or if clauses. The returned result is a list generated from the subsequent for and if context according to the expression. If you want the expression to derive a tuple, you must use parentheses.
Multiply each value in the list by three to get a new list:
vec = [2, 4, 6] [(x, x**2) for x in vec] # [(2, 4), (4, 16), (6, 36)]
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']
Use the if clause as the filter:
vec = [2, 4, 6] [3*x for x in vec if x > 3] # [12, 18]
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] [vec1[i]*vec2[i] for i in range(len(vec1))] # [8, 12, -54]
List nesting resolution:
matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9], ] new_matrix = [[row[i] for row in matrix] for i in range(len(matrix[0]))] print(new_matrix) # [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
Tuple
-
Tuples are similar to lists, except that the elements of tuples cannot be modified
-
Tuples use parentheses and lists use square brackets
-
Tuple creation is simple. You only need to add elements in parentheses and separate them with commas
-
There is no method to modify such as append(), insert(), and other methods are the same as the list
-
The key in the dictionary must be unique and immutable, and the value is unlimited
-
When a tuple contains only one element, you need to add a comma after the element, otherwise the parentheses will be used as operators
Access tuple
Tuples are accessed in the same way as lists. The element of a tuple can be directly assigned to multiple variables, but the number of variables must be consistent with the number of elements.
a, b, c = (1, 2, 3) print(a, b, c)
Combinatorial tuple
The element values in tuples are not allowed to be modified, but we can connect and combine tuples
tup1 = (12, 34.56); tup2 = ('abc', 'xyz') tup3 = tup1 + tup2; print (tup3) # (12, 34.56, 'abc', 'xyz')
Delete tuple
Element values in tuples are not allowed to be deleted, but we can use del statement to delete the whole tuple
tuples function
-
len(tuple) number of tuple elements
-
max(tuple) the maximum value in the tuple element
-
min(tuple) minimum value in tuple element
-
tuple(tuple) converts a list to tuples
Tuple derivation
t = 1, 2, 3 print(t) # (1, 2, 3) u = t, (3, 4, 5) print(u) # ((1, 2, 3), (3, 4, 5))
Dictionary (dict)
-
A dictionary is another variable container model that can store objects of any type
-
Each key value (key = > value) pair of the dictionary is separated by colon (:), and each pair is separated by comma (,). The whole dictionary is included in curly braces ({})
-
Keys must be unique, but values do not
-
The value can be any data type
-
Keys must be immutable, such as numbers, strings, tuples, but not lists
-
If you use a key not in the dictionary to access data, an error will be reported
-
The elements of the dictionary have no order and cannot be referenced by subscript or key
-
The order in which keys are stored in the dictionary has nothing to do with the order in which keys are placed
The format is as follows:
d = {key1 : value1, key2 : value2 }
ACCESS Dictionary
dis = {'a': 1, 'b': [1, 2, 3]} print(dis['b'][2])
Modify dictionary
dis = {'a': 1, 'b': [1, 2, 3], 9: {'name': 'hello'}} dis[9]['name'] = 999 print(dis) # {'a': 1, 9: {'name': 999}, 'b': [1, 2, 3]}
Delete dictionary
Delete the dictionary or dictionary elements with the del statement.
dis = {'a': 1, 'b': [1, 2, 3], 9: {'name': 'hello'}} del dis[9]['name'] print(dis) del dis # Delete dictionary # {'a': 1, 9: {}, 'b': [1, 2, 3]}
Dictionary function
-
len(dict) calculates the number of dictionary elements, that is, the total number of keys
-
str(dict) outputs a dictionary, represented as a printable string
-
type(variable) returns the type of the input variable. If the variable is a dictionary, it returns the dictionary type
-
key in dict determines whether the key exists in the dictionary
Dictionary method
dic1 = {'a': 'a'} dic2 = {9: 9, 'a': 'b'} dic1.update(dic2) print(dic1) # {'a': 'b', 9: 9}
-
dict.clear()
Delete all elements in the dictionary
-
dict.copy()
Returns a shallow copy of a dictionary
-
dict.fromkeys(seq[, value])
Create a new dictionary, use the element in seq sequence as the key of the dictionary, and value is the initial value corresponding to all the keys of the dictionary
-
dict.get(key, default=None)
Returns the value of the specified key. If the value is not in the dictionary, it returns the default value
-
dict.items()
Returns an array of traversable (key, value) tuples in list form
-
dict.keys()
Returns all keys of a dictionary in a list
-
dict.values()
Returns all values in the dictionary as a list
-
dict.setdefault(key, default=None)
If the key is in the dictionary, the corresponding value is returned. If it is not in the dictionary, insert the key and the set default value default, and return default. The default value is None.
-
dict.update(dict2)
Update the key / value pair of dictionary parameter dict2 to dictionary dict
-
dict.pop(key[,default])
Delete the value corresponding to the key given in the dictionary, and the return value is the deleted value. The key value must be given, otherwise the default value is returned.
-
dict.popitem()
Randomly return and delete a pair of keys and values in the dictionary (generally delete the end pair)
Dictionary derivation
The constructor dict() builds a dictionary directly from the list of key value pair tuples. If there is a fixed pattern, the list derivation specifies a specific key value pair:
>>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)]) {'sape': 4139, 'jack': 4098, 'guido': 4127}
In addition, dictionary derivation can be used to create an expression dictionary for any key and value:
>>> {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 using keyword parameters:
>>> dict(sape=4139, guido=4127, jack=4098) {'sape': 4139, 'jack': 4098, 'guido': 4127}
Set
A collection is an unordered sequence of non repeating elements
Create collection
-
You can create a collection using braces {} or the set() function
-
To create an empty collection, you must use set() instead of {}, because {} is used to create an empty dictionary
-
set(value) creates a set. Value can be string, list, tuple, dictionary and other sequence types
-
Create, add, modify and other operations, the collection will be automatically de duplicated
{1, 2, 1, 3} # {} {1, 2, 3} set('12345') # String {'3', '5', '4', '2', '1'} set([1, 'a', 23.4]) # List {1, 'a', 23.4} set((1, 'a', 23.4)) # Tuple {1, 'a', 23.4} set({1:1, 'b': 9}) # Dictionary {1, 'b'}
Add element
Add the element val to the set. If the element already exists, no operation will be performed:
set.add(val)
You can also use the update method to add elements in batches. The parameters can be lists, tuples, dictionaries, etc
set.update(list1, list2,...)
Removing Elements
If the element val exists, it will be removed. If it does not exist, an error will be reported:
set.remove(val)
If the element val exists, it will be removed. If it does not exist, no error will be reported:
set.discard(val)
Remove an element at random:
set.pop()
Number of elements
Like other sequences, you can use len(set) to get the number of elements in the set.
Empty collection
set.clear() set = set()
Determine whether the element exists
val in set
Other methods
-
set.copy()
Copy Collection
-
set.difference(set2)
The difference set is found in set but not in set2
-
set.intersection(set2)
Find the intersection, which exists in both set and set2
-
set.union(set2)
Union, all elements of set and set2
-
set.symmetric_difference(set2)
Find the elements that appear in the two sets at different times
-
set.isdisjoint(set2)
Returns True if two collections do not have the same element
-
set.issubset(set2)
Returns True if set is a subset of set2
-
set.issuperset(set2)
Returns True if set is a superset of set2
Set computing
a = set('abracadabra') b = set('alacazam') print(a) # The only letter in a # {'a', 'r', 'b', 'c', 'd'} print(a - b) # The letter in a, but not in b # {'r', 'd', 'b'} print(a | b) # Letters in a or b # {'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'} print(a & b) # Letters in both a and b # {'a', 'c'} print(a ^ b) # A letter in a or b, but not in both a and b # {'r', 'd', 'b', 'm', 'z', 'l'}
Set derivation
a = {x for x in 'abracadabra' if x not in 'abc'} print(a) # {'d', 'r'}
Process control
if control
if Expression 1: sentence if Expression 2: sentence elif Expression 3: sentence else: sentence elif Expression 4: sentence else: sentence
1. Each condition should be followed by a colon:, indicating the statement block to be executed after the condition is met. 2. Indent is used to divide statement blocks. Statements with the same number of indents form a statement block. 3. There is no switch - case statement in Python.
Ternary operator:
<Expression 1> if <condition> else <Expression 2>
When writing conditional statements, you should try to avoid using nested statements. Nested statements are not easy to read and may ignore some possibilities.
for traversal
for <Cyclic variable> in <Loop object>: <Statement 1> else: <Statement 2>
Statement 2 in else statement is executed only when the loop exits normally (after traversing the values in all traversed objects).
When traversing the dictionary, the keyword and the corresponding value can be interpreted simultaneously using the {items() method:
knights = {'gallahad': 'the pure', 'robin': 'the brave'} for k, v in knights.items(): print(k, v)
When traversing the sequence, the index position and corresponding value can be obtained simultaneously by using the {enumerate() function:
for i, v in enumerate(['tic', 'tac', 'toe']): print(i, v)
To traverse two or more sequences at the same time, you can use the zip() combination:
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))
To traverse a sequence backwards, first specify the sequence and then call the reversed() function:
for i in reversed(range(1, 10, 2)): print(i)
To traverse a sequence in order, use the {sorted() function to return a sorted sequence without modifying the original value:
basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'] for f in sorted(set(basket)): print(f)
while loop
while<condition>: <Statement 1> else: <Statement 2>
break,continue,pass
Break statements are used in while and for loops. Break statements are used to terminate loop statements, that is, if the loop condition has no False condition or the sequence has not been completely recursive, the execution of loop statements will also be stopped. The continue statement is used in the while and for loops. The continue statement is used to tell Python to skip the remaining statements of the current loop and then continue to the next loop. The continue statement jumps out of this loop, and the break statement jumps out of the entire loop.
pass is an empty statement to maintain the integrity of the program structure. pass does nothing. It is generally used as a placeholder statement.
iterator
-
An iterator is an object that remembers where to traverse.
-
The iterator object is accessed from the first element of the collection until all the elements are accessed. Iterators can only move forward, not backward.
-
Iterators have two basic methods: iter() and {next().
-
String, list, or tuple objects can be used to create iterators.
Iterators can be traversed by a for loop:
li = [1, 2, 3] it = iter(li) for val in it: print(val)
The iterator can also use the next() function to access the next element value:
import sys li = [1,2,3,4] it = iter(li) while True: try: print (next(it)) except StopIteration: sys.exit()
generator
-
In Python, functions that use yield are called generator s.
-
Different from ordinary functions, a generator is a function that returns an iterator and can only be used for iterative operations. It is easier to understand that a generator is an iterator.
-
In the process of calling the generator to run, each time a yield is encountered, the function will pause and save all the current running information, return the value of yield, and continue to run from the current position the next time the next() method is executed.
-
Call a generator function and return an iterator object.
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 is an iterator that is returned by the generator while True: try: print(next(f)) except StopIteration: sys.exit()
function
Custom function
Functions refer to reusable program fragments. They allow you to give a name to a code block, allow you to run the code block anywhere in your program with this special name, and can be repeated any number of times. This is called Calling functions.
-
The function code block begins with the "def" keyword, followed by the function identifier name and parentheses ().
-
Any incoming parameters and arguments must be placed between parentheses, which can be used to define parameters.
-
The first line of the function can optionally use a document string - used to hold the function description.
-
The function content starts with a colon and is indented.
-
Return [expression] ends the function and optionally returns a value to the caller. A return without an expression is equivalent to returning None.
-
return: multiple values can be returned. At this time, the returned data is not of tuple type.
-
When defining parameters, parameters with default values must be followed by parameters without default values.
def Function name (parameter list): Function body
Parameter transfer
In Python, a type belongs to an object, and a variable has no type:
a = [1,2,3] a = "Runoob"
In the above code, [1,2,3] is a List type, "Runoob" is a String type, and variable a has no type. It is just a reference (a pointer) to an object, which can point to a List type object or a String type object.
Changeable and unchangeable objects
In Python, strings, numbers, and tuples are immutable objects, while lists, dictionaries, and so on are modifiable objects.
-
Immutable type: the variable is assigned a=5 and then a=10. Here, in fact, an int value object 10 is newly generated, and then a points to it, while 5 is discarded. Instead of changing the value of a, it is equivalent to newly generating a.
-
Variable type: if the variable is assigned la=[1,2,3,4] and then assigned la[2]=5, the value of the third element of list la is changed. la itself does not move, but some of its internal values are modified.
Parameter passing of Python function:
-
Immutable type: value transfer similar to c + +, such as integer, string and tuple. For example, in fun (a), only the value of a is passed, which does not affect the object itself. For example, modifying the value of a within fun (a) only modifies another copied object, which does not affect the object itself.
-
Variable type: reference passing similar to c + +, such as lists and dictionaries. For example, if fun (la) is used, the la will be really passed over, and the la outside the modified fun will also be affected
Everything in Python is an object. Strictly speaking, we can't say value passing or reference passing. We should say passing immutable objects and variable objects.
parameter
Required parameters
Required parameters must be passed into the function in the correct order. The number of calls must be the same as when declared.
Keyword parameters
Keyword parameters are closely related to function calls. Function calls use keyword parameters to determine the incoming parameter values. Using keyword parameters allows the order of parameters when calling a function to be inconsistent with that when declared, because the Python interpreter can match parameter values with parameter names.
def print_info(name, age): "Print any incoming strings" print("name: ", name) print("Age: ", age) return print_info(age=50, name="john")
Default parameters
When a function is called, if no parameters are passed, the default parameters are used.
def print_info(name, age=35): print ("name: ", name) print ("Age: ", age) return print_info(age=50, name="john") print("------------------------") print_info(name="john")
Indefinite length parameter
-
Parameters marked with an asterisk * will be imported as tuples to store all unnamed variable parameters.
-
If no parameters are specified in the function call, it is an empty tuple. We can also not pass unnamed variables to the function.
def print_info(arg1, *vartuple): print("output: ") print(arg1) for var in vartuple: print (var) return print_info(10) print_info(70, 60, 50)
-
Parameters with two asterisks * * will be imported in the form of a dictionary. The variable name is the key, and the variable value is the dictionary element value.
def print_info(arg1, **vardict): print("output: ") print(arg1) print(vardict) print_info(1, a=2, b=3)
Anonymous function
Python uses lambda to create anonymous functions.
The so-called anonymity means that a function is no longer defined in the standard form of "def" statement.
Lambda is just an expression, and the function body is much simpler than def. The body of a lambda is an expression, not a code block. Only limited logic can be encapsulated in lambda expressions. Lambda functions have their own namespace and cannot access parameters outside their own parameter list or in the global namespace. Although lambda functions can only write one line, they are not equivalent to C or C + + inline functions. The purpose of the latter is to call small functions without occupying stack memory, so as to increase operation efficiency.
# Syntax format lambda [arg1 [,arg2,.....argn]]:expression
Variable scope
-
L (Local) Local scope
-
E (Enclosing) in functions other than closure functions
-
G (Global) Global scope
-
B (build in) built in scope
Search according to the rules of L – > e – > G – > b, that is, if it cannot be found locally, it will go to the local outside the local (such as closure), if it cannot be found again, it will go to the global, and then go to the built-in.
In Python, only module s, class es and functions (def and lambda) will introduce new scopes. Other code blocks (such as if/elif/else /, try/except, for/while, etc.) will not introduce new scopes. That is, the variables defined in these statements can also be accessed externally.
Variables defined inside the function have a local scope, and variables defined outside the function have a global scope.
Local variables can only be accessed inside the declared function, while global variables can be accessed throughout the program. When a function is called, all variable names declared within the function are added to the scope.
When the internal scope wants to modify the variables of the external scope, the global and nonlocal keywords are used.
num = 1 def fun1(): global num # global keyword declaration is required print(num) num = 123 print(num) fun1()
If you want to modify variables in a nested scope (enclosing scope, outer non global scope), you need the nonlocal keyword.
def outer(): num = 10 def inner(): nonlocal num # nonlocal keyword declaration num = 100 print(num) inner() print(num) outer()
modular
There are many ways to write a module, the simplest of which is to create a module containing functions and variables py is the suffix of the file.
Another approach is to write modules in the native language of the Python interpreter itself. For example, you can write Python modules in C language, and after compilation, you can use them in your Python code through the standard Python interpreter.
A module is a file that contains all the functions and variables you define. Its suffix is py. The module can be introduced by other programs to use the functions in the module. This is also the way to use the Python standard library.
When the interpreter encounters an import statement, 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 a module, you need to put the command at the top of the script.
A module is imported only once, which prevents the imported module from being executed over and over again.
The search path is stored in the path variable in the sys module. The current directory refers to the directory where the program starts.
Import module
Import module:
import module1[, module2[,... moduleN]]
Import a specified part from the module into the current namespace:
from modname import name1[, name2[, ... nameN]]
Import all contents of a module into the current namespace:
from modname import *
__ name__ attribute
Each module has one__ name__ Property when its value is' '__ main__' It indicates that the module itself is running, otherwise it is introduced.
When a module is first introduced by another program, its main program will run. If we want a program block in the module not to execute when the module is introduced, we can use__ name__ Property to make the block execute only when the module itself is running.
if __name__ == '__main__': print('The program itself is running') else: print('The first mock exam is from another module.')
dir function
The built-in function dir() can find all the names defined in the module. Returns as a list of strings.
If no parameter is given, the dir() function lists all the currently defined names.
In Python, everything is an object. In fact, built-in data types such as int, str, float, list and tuple are also classes. You can also use dir(int) to view all the methods contained in int. You can also use 'help(int) to view help information for the' Int 'class.
package
Package is a form of managing Python module namespace, which adopts "point module name".
For example, if the name of a module is A.B, it represents sub module B in package a.
Just as you don't have to worry about the interaction of global variables between different modules when using modules, you don't have to worry about the duplicate names of modules between different libraries in the form of point module names.
When importing a package, Python will import it according to sys Path to find the subdirectories contained in the package.
The directory contains only one file called__ init__.py file will be regarded as a package, mainly to avoid some vulgar names (such as string) inadvertently affecting the effective modules in the search path.
In the simplest case, put an empty one__ init__.py file is OK. Of course, this file can also contain some initialization code or__ all__ Variable assignment.
Third party module
-
easy_ Both install and pip are used to download and install resource packages related to PyPI, a public resource library of Python. Pip is easy_ The improved version of install provides better prompt information, delete package and other functions. In the old version of python, there was only easy_install, no pip.
-
easy_install packages and publishes Python packages, and pip is package management.
easy_ Usage of install:
easy_install Package name easy_install "Package name == Version number of the package"
easy_install -U "Package name >= Version number of the package"
-
Install a package
-
Upgrade a package
Usage of pip:
pip install Package name pip install Package name == Version number of the package
pip install —upgrade Package name >= Version number of the package
pip uninstall Package name
pip list
-
Install a package
-
Upgrade a package (if the version number is not provided, upgrade to the latest version)
-
Delete a package
-
List of installed packages
object-oriented
Class and Object are two main aspects of Object-oriented programming. A class can create a new Type, in which the Object is the Instance of the class. It can be analogized as follows: you can have a variable of Type int, that is, the variable storing integers is the Instance (Object) of class int.
-
Class: used to describe a collection of objects with the same properties and methods. It defines the properties and methods common to each object in the collection. An object is an instance of a class.
-
Method: a function defined in a class.
-
Class variables: class variables are common to the entire instantiated object. Class variables are defined in the class and outside the function body. Class variables are usually not used as instance variables.
-
Data members: class variables or instance variables are used to process data related to classes and their instance objects.
-
Method override: if the method inherited from the parent class cannot meet the needs of the child class, it can be overridden. This process is called method override, also known as method override.
-
Instance variable: the variable defined in the method, which only works on the class of the current instance.
-
Inheritance: that is, a derived class inherits the fields and methods of the base class. Inheritance also allows the object of a derived class to be treated as a base class object. For example, there is such a design: an object of Dog type derives from the Animal class, which simulates the "is-a" relationship (for example, Dog is an Animal).
-
Instantiation: create an instance of a class and a concrete object of the class.
-
Object: an instance of a data structure defined by a class. The object consists of two data members (class variables and instance variables) and methods.
Classes in Python provide all the basic functions of object-oriented programming: the inheritance mechanism of classes allows multiple base classes, derived classes can override any method in the base class, and methods with the same name in the base class can be called.
Objects can contain any number and type of data.
self
Self represents the current instance and represents the address of the current object. Class consists of self__ class__ Indicates.
Self , is not a keyword, and other names can be substituted, but , self , is a general standard name.
class
Class is created by the {class} keyword. After a class is instantiated, its properties can be used. In fact, after a class is created, its properties can be accessed through the class name.
Object method
The method is defined by the "def" keyword. Unlike the function, the method must contain the parameter "self", which is the first parameter. Self "represents an instance of this class.
Class method
The decorator @ classmethod # can identify a method as a class method. The first parameter of a class method must be cls instead of self.
Static method
The decorator @ staticmethod , can identify a method as a static method. The first parameter of the static method is no longer specified, so you don't need {self} or} cls.
__ init__ method
__ init__ Method is the construction method. It will run first when the object of the class is instantiated. You can put the initialization operation into the method.
If rewritten__ init__, Instantiating a subclass will not call the defined by the parent class__ init__.
variable
Class variables are Shared -- they can be accessed by all instances of the class. The Class Variable has only one copy. When any object changes the Class Variable, the changes will be reflected in all other instances.
Object variable s are owned by each independent object or instance of the class. In this case, each object has a copy of its own field, that is, they will not be shared or associated in any way with fields with the same name in other different instances.
In Python, variable names are similar__ xxx__ , which starts with a double underscore and ends with a double underscore, are special variables. Special variables can be accessed directly, not private variables. Therefore, they cannot be used__ name__,__ score__ Such variable names.
access control
-
Private property
__ private_attr: it starts with two underscores and declares that the attribute is private and cannot be used or directly accessed outside the class.
-
Private method
__ private_method: it starts with two underscores and declares that the method is private. It can only be called inside the class, not outside the class.
We also consider the convention that properties or methods that begin with an underscore are protected. For example_ protected_attr,_ protected_method.
inherit
Class can inherit, and supports inheriting multiple parent classes. When defining a class, specify the parent class to inherit in parentheses after the class name, and multiple parent classes are separated by commas.
Instances of subclasses have full access to the non private properties and methods of all inherited parent classes.
If there is the same method name in the parent class and it is not specified when the child class is used, Python searches from left to right, that is, if the method is not found in the child class, it searches from left to right whether the parent class contains the method.
Method rewrite
The method of a subclass can override the method of a parent class. Overridden method parameters are not required to be consistent, but reasonable designs should be consistent.
The super() function can call a method of the parent class to solve the multi inheritance problem.
Class specific methods:
-
__ init__: Constructor, called when the object is generated
-
__ del__: Destructor, used when releasing an object
-
__ repr__: Printing, converting
-
__ setitem__: Assignment by index
-
__ getitem__: Get value by index
-
__ len__: Get length
-
__ cmp__: Comparison operation
-
__ call__: function call
-
__ add__: Addition operation
-
__ sub__: Subtraction operation
-
__ mul__: Multiplication operation
-
__ div__: Division operation
-
__ mod__: Remainder operation
-
__ pow__: Power
Class's proprietary methods also support overloading.
example
class Person: """Personnel information""" # Name (common attribute) name = '' # Age (common attribute) age = 0 def __init__(self, name='', age=0): self.name = name self.age = age # Overload proprietary methods:__ str__ def __str__(self): return "It's overloaded here __str__ Proprietary method, " + str({'name': self.name, 'age': self.age}) def set_age(self, age): self.age = age class Account: """Account information""" # Account balance (private attribute) __balance = 0 # Total of all accounts __total_balance = 0 # Get account balance # self must be the first parameter of the method def balance(self): return self.__balance # Increase account balance def balance_add(self, cost): # self accesses this instance self.__balance += cost # self.__class__ Can access classes self.__class__.__total_balance += cost # Class method (identified by @ classmethod, the first parameter is cls) @classmethod def total_balance(cls): return cls.__total_balance # Static method (identified by @ staticmethod, no class parameter or instance parameter is required) @staticmethod def exchange(a, b): return b, a class Teacher(Person, Account): """teacher""" # Class name _class_name = '' def __init__(self, name): # The first overloaded parent class__ init__ () construction method # Super (subclass, self)__ init__ (parameter 1, parameter 2,...) super(Teacher, self).__init__(name) def get_info(self): # Returns personal information as a dictionary return { 'name': self.name, # The property value of the parent class Person is accessed here 'age': self.age, 'class_name': self._class_name, 'balance': self.balance(), # Methods overloaded by subclasses are called here } # Method overloading def balance(self): # Account.__balance is a private property and cannot be accessed by subclasses, so the parent class provides methods to access it return Account.balance(self) * 1.1 class Student(Person, Account): """student""" _teacher_name = '' def __init__(self, name, age=18): # The second overloaded parent class__ init__ () construction method # Parent class name__ init__(self, parameter 1, parameter 2,...) Person.__init__(self, name, age) def get_info(self): # Returns personal information as a dictionary return { 'name': self.name, # The property value of the parent class Person is accessed here 'age': self.age, 'teacher_name': self._teacher_name, 'balance': self.balance(), } # Teacher John john = Teacher('John') john.balance_add(20) john.set_age(36) # An instance of a subclass can directly call the methods of the parent class print("John's info:", john.get_info()) # Student Mary mary = Student('Mary', 18) mary.balance_add(18) print("Mary's info:", mary.get_info()) # Student Fake fake = Student('Fake') fake.balance_add(30) print("Fake's info", fake.get_info()) # There are three different ways to call static methods print("john.exchange('a', 'b'):", john.exchange('a', 'b')) print('Teacher.exchange(1, 2)', Teacher.exchange(1, 2)) print('Account.exchange(10, 20):', Account.exchange(10, 20)) # Class method, class attribute print('Account.total_balance():', Account.total_balance()) print('Teacher.total_balance():', Teacher.total_balance()) print('Student.total_balance():', Student.total_balance()) # Overload proprietary method print(fake)
Output:
John's info: {'name': 'John', 'age': 36, 'class_name': '', 'balance': 22.0} Mary's info: {'name': 'Mary', 'age': 18, 'teacher_name': '', 'balance': 18} Fake's info {'name': 'Fake', 'age': 18, 'teacher_name': '', 'balance': 30} john.exchange('a', 'b'): ('b', 'a') Teacher.exchange(1, 2) (2, 1) Account.exchange(10, 20): (20, 10) Account.total_balance(): 0 Teacher.total_balance(): 20 Student.total_balance(): 48 It's overloaded here __str__ Proprietary method, {'name': 'Fake', 'age': 18}
Errors and exceptions
syntax error
The syntax error class represents a syntax error that will be triggered when the interpreter finds that the code cannot pass the syntax check. Syntax error is unable to use {try except... Captured.
>>> print: File "<stdin>", line 1 print: ^ SyntaxError: invalid syntax
abnormal
Even if the syntax of the program is correct, errors may occur when running it. An error that occurs at runtime is called an exception. The front part of the error message shows the context in which the exception occurred, and displays the specific information in the form of call stack.
>>> 1 + '0' Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unsupported operand type(s) for +: 'int' and 'str'
exception handling
Python provides {try except ... Syntax structure to catch and handle exceptions.
The execution process of try statement is as follows:
-
First, execute the try clause (the statement between the keyword try and the keyword except)
-
If no exception occurs, the exception clause is ignored and the try clause ends after execution.
-
If an exception occurs during the execution of the try clause, the rest of the try clause is ignored. If the exception type matches the name after exception, the corresponding exception clause will be executed. Finally, execute the code after the try statement.
-
If an exception does not match any except, the exception will be passed to the upper try.
-
A try statement may contain multiple except clauses to handle different specific exceptions.
-
At most one except clause will be executed.
-
The handler will only handle exceptions in the corresponding try clause, not exceptions in other try handlers.
-
An exception clause can handle multiple exceptions at the same time. These exceptions will be placed in a bracket as a tuple.
-
The last exception clause ignores the name of the exception and will be used as a wildcard. You can use this method to print an error message and then throw the exception again.
-
The try except statement also has an optional else clause. If this clause is used, it must be placed after all except clauses. This clause will be executed when no exception occurs in the try clause.
-
Exception handling does not only deal with exceptions that happen directly in the try clause, but also handles exceptions thrown in functions that are called in the clause (or even indirectly called functions).
-
The finally clause is executed regardless of whether an exception occurs in the try clause.
-
If an exception is thrown in the try clause (or in the except and else clauses) and no exception intercepts it, the exception will be thrown again after the finally clause is executed.
Throw exception
Use the raise statement to throw a specified exception.
The only argument to raise specifies the Exception to be thrown. It must be an instance of an Exception or an Exception class (that is, a subclass of Exception).
If you just want to know if this throws an exception and don't want to deal with it, a simple raise statement can throw it again.
Custom exception
You can have your own Exception by creating a new Exception class. The Exception class inherits from the Exception class and can inherit directly or indirectly.
When creating a module may throw many different exceptions, a common approach is to create a basic exception class for the package, and then create different subclasses for different error conditions based on the basic class.
Most exception names end with "Error", just like standard exception names.
example
import sys class Error(Exception): """Base class for exceptions in this module.""" pass # Custom exception 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 try: print('code start running...') raise InputError('input()', 'input error') # ValueError int('a') # TypeError s = 1 + 'a' dit = {'name': 'john'} # KeyError print(dit['1']) except InputError as ex: print("InputError:", ex.message) except TypeError as ex: print('TypeError:', ex.args) pass except (KeyError, IndexError) as ex: """Support to handle multiple exceptions at the same time, Put parentheses in tuples""" print(sys.exc_info()) except: """Catch other unspecified exceptions""" print("Unexpected error:", sys.exc_info()[0]) # raise is used to throw an exception raise RuntimeError('RuntimeError') else: """When there is no abnormality, Will execute else clause""" print('"else" clause...') finally: """Whether there is abnormality or not, Will be implemented finally""" print('finally, ending')
File operation
Open file
The open() function is used to open / create a file and return a file object:
open(filename, mode)
-
filename: a string value containing the name of the file you want to access
-
Mode: determines the mode of opening the file: read-only, write, append, etc
File open mode:
File object method
-
fileObject.close()
The close() method is used to close an open file. The closed file cannot be read or written again, otherwise a ValueError error will be triggered. The close() method allows multiple calls.
When the file object is referenced to operate another file, Python will automatically close the previous file object. It is a good practice to close files using the close() method.
-
fileObject.flush()
The flush() method is used to flush the buffer, that is, the data in the buffer is immediately written to the file, and the buffer is emptied at the same time. There is no need to wait passively for the output buffer to be written.
Generally, the buffer will be refreshed automatically after the file is closed, but sometimes you need to refresh it before closing. At this time, you can use the flush() method.
-
fileObject.fileno()
The fileno() method returns an integer file descriptor (FD integer), which can be used for I/O operations of the underlying operating system.
-
fileObject.isatty()
The isatty() method detects whether the file is connected to a terminal device. If yes, it returns True; otherwise, it returns False.
-
next(iterator[,default])
The File object in Python 3 does not support the next() method. Python 3's built-in function {next() is called through an iterator__ next__ The () method returns the next item. In the loop, the next () function is invoked in each loop, which returns the next line of the File and triggers StopIteration if it reaches the end (EOF).
-
fileObject.read()
The read() method is used to read the specified number of bytes from the file. If it is not given or negative, all bytes are read.
-
fileObject.readline()
The readline() method is used to read the entire line from the file, including the "\ n" character. If a non negative parameter is specified, the number of bytes of the specified size, including the "\ n" character, is returned.
-
fileObject.readlines()
The readlines() method is used to read all lines (up to the terminator EOF) and return a list, which can be used by Python's {for in ... Structure. If the terminator EOF is encountered, an empty string is returned.
-
fileObject.seek(offset[, whence])
The seek() method is used to move the file read pointer to the specified location.
The value of where, if 0, indicates the beginning, if 1, indicates the current location, and 2 indicates the end of the file. The default value of where is 0, which is the beginning of the file. For example:
seek(x, 0): move x characters from the starting position, that is, the first character of the first line of the file
seek(x, 1): indicates to move x characters backward from the current position
seek(-x, 2): move x characters forward from the end of the file
-
fileObject.tell(offset[, whence])
The tell() method returns the current location of the file, that is, the current location of the file pointer.
-
fileObject.truncate([size])
truncate() method is used to truncate the file from the first character of the first line. Truncate the file to size characters. No size means truncate from the current position; After truncation, all characters after V are deleted, and the newline under the windows system represents the size of 2 characters.
-
fileObject.write([str])
The write() method writes the specified string to the file.
Before the file is closed or the buffer is refreshed, the string content is stored in the buffer. At this time, you can't see the written content in the file.
If the file opening mode is b, when writing the file content, str (parameter) should be converted to bytes using the encode method. Otherwise, an error is reported: typeerror: a bytes like object is required, not 'STR'.
-
fileObject.writelines([str])
The writelines() method writes a sequence of strings to a file. This sequence string can be generated by iterative objects, such as a string list. Newline requires a newline character \ n.
example
filename = 'data.log' # Open file (a + append read / write mode) # Opening a file with the keyword will automatically close the file resource with open(filename, 'w+', encoding='utf-8') as file: print('File name: {}'.format(file.name)) print('Document code: {}'.format(file.encoding)) print('File open mode: {}'.format(file.mode)) print('Is the file readable: {}'.format(file.readable())) print('Is the file writable: {}'.format(file.writable())) print('The file pointer position is: {}'.format(file.tell())) # Write content num = file.write("First line content\n") print('write file {} Characters'.format(num)) # The file pointer is at the end of the file, so there is no content print(file.readline(), file.tell()) # Change the file pointer to the file header file.seek(0) # After changing the file pointer, read the first line print(file.readline(), file.tell()) # However, the change of file pointer will not affect the write position file.write('Second write\n') # The file pointer returns to the end of the file print(file.readline(), file.tell()) # file.read() reads a character of the specified length from the current file pointer position file.seek(0) print(file.read(9)) # Split the file by line and return a list of strings file.seek(0) print(file.readlines()) # Iterate over file objects, one element per line file.seek(0) for line in file: print(line, end='') # Close file resource if not file.closed: file.close()
Output:
File name: data.log Document code: utf-8 File open mode: w+ Is the file readable: True Is the file writable: True The file pointer position is: 0 Write file 6 characters 16 First line content 16 41 First line content The second time ['First line content\n', 'Second write\n'] First line content Second write
serialize
In Python, the pickle module implements the serialization and deserialization of data. Pickle supports any data type, including built-in data types, functions, classes, objects, etc.
method
dump
Serialize the data object and write it to the file
pickle.dump(obj, file, protocol=None, fix_imports=True)
The required parameter obj indicates the object to be encapsulated. The required parameter file indicates the file object to be written by obj. File must be opened in binary writable mode, i.e. wb. The optional parameter protocol indicates the protocol used by pickle. The supported protocols are 0,1,2,3. The default protocol is protocol 3 added to Python 3.
load
Read content from file and deserialize
pickle.load(file, fix_imports=True, encoding='ASCII', errors='strict')
Required parameter file must be opened in binary readable mode, i.e. rb, and others are optional parameters.
dumps
Returns the encapsulated object in the form of byte object, which does not need to be written to the file
pickle.dumps(obj, protocol=None, fix_imports=True)
loads
Read the encapsulated object from the byte object and return
pickle.loads(bytes_object, fix_imports=True, encoding='ASCII', errors='strict')
example
import pickle data = [1, 2, 3] # Serialize data and return as a byte object dumps_obj = pickle.dumps(data) print('pickle.dumps():', dumps_obj) # Deserialize data from a byte object loads_data = pickle.loads(dumps_obj) print('pickle.loads():', loads_data) filename = 'data.log' # Serialize data into a file with open(filename, 'wb') as file: pickle.dump(data, file) # Load and deserialize from file with open(filename, 'rb') as file: load_data = pickle.load(file) print('pickle.load():', load_data)
Output:
pickle.dumps(): b'\x80\x03]q\x00(K\x01K\x02K\x03e.' pickle.loads(): [1, 2, 3] pickle.load(): [1, 2, 3]
Naming conventions
Guido, the father of Python, recommended specifications
It's quite long, but all the basic content about python is basically completely covered. What basic knowledge you don't understand can be searched here at any time. Favorite friends can collect it for easy learning. Come on!!