Portal:By the end of this article, your Linux base is pretty much there

preface

This article is based on the Python Foundation class of 2018 by Dark Horse Programmers. It is based on the data of 2018 and supplemented by the data of 2016. It also refers to some online tutorials to better summarize the basic knowledge of Python. The article is divided into two parts, basic Python syntax and object orientation.

Part 1 Basic Python syntax

1. Know the Python

1.1 introduction of Python

Python was founded by Guido van Rossum.

Python’s design goals:

  • A simple, intuitive language and as powerful as the main competitors
  • Open source so that anyone can contribute to it
  • The code is as easy to understand as plain English
  • Suitable for daily tasks of short-term development

Python design philosophy:

  • Elegant, clear and simple

The Philosophy of Python developers is: one way, preferably only one way, to do one thing

Python is a fully object-oriented language, in which everything is an object.

Extensibility: If you need a key piece of code to run faster or you want to keep some algorithms private, you can write it in C or C++ and use it in A Python program.

1.2. First Python program

There are three ways to run Python programs: interpreter, interactive, and IDE

Python is a very rigidly formatted programming language. Python 2.x does not support Chinese by default.

  • ASCIIThe character contains only256Is a string of characters. Chinese is not supported
  • The interpreter name for Python 2.x is Python
  • The interpreter name for Python 3.x is python3

A transitional version, Python 2.6, is officially available to accommodate existing programs.

Tip: If Python 3.0 is not immediately available for development (there are few third-party libraries that do not support the 3.0 syntax), it is recommended

  • Use the firstPython 3.0Version development
  • Then use thePython 2.6,Python 2.7To execute, and do some compatibility

IPython is a Python interactive shell that is much easier to use than the default Python shell. It supports bash shell commands and is suitable for learning/validating Python syntax or local code.

Integrated Development Environment (IDE) — Integrates all the tools needed to develop software, typically including the following tools:

  • Graphical user interface
  • Code editor (code completion/auto indent support)
  • Compiler/interpreter
  • Debugger (breakpoint/step)

1.3. PyCharm setting

The PyCharm configuration information is stored in the.pyCharmXXXX. x directory in the user’s home directory, where xxxx.x represents the version number of PyCharm currently in use

1.3.1 Restoring PyCharm initial Settings
    1. Close PyCharm that is running
    1. On the terminal, run the following terminal command to delete the PyCharm configuration directory:
$rm - r ~ /. PyCharm2016.3Copy the code
    1. Restart PyCharm
1.3.2 PyCharm Installation and Startup Procedure
    1. Run the following command to decompress the downloaded installation package
$tar - ZXVF pycharm - professional - 2017.1.3. Tar. GzCopy the code
    1. Move the decompressed directory to/optIn the directory, it is convenient for other users to use

/opt directory The user stores additional software for the host

$sudo mv pycharm-2017.1.3/ /opt/Copy the code
    1. Switching working Directory
$ cdThe/opt/pycharm - 2017.1.3 / binCopy the code
    1. Start the PyCharm
$ ./pycharm.sh
Copy the code
1.3.3 Setting the startup icon
  • In the Professional edition, select the menu Tools/Create Desktop Entry… You can set the taskbar startup icon
  • Note: This parameter needs to be selected when setting the iconCreate the entry for all users Shortcut file /usr/share/applications/jetbrains-pycharm.desktop

In Ubuntu, shortcuts to application startup are usually saved in the /usr/share/applications directory

Uninstall PyCharm from previous versions

To uninstall PyCharm, you only need to do the following two steps:

    1. Delete the decompressed directory
$sudo rm -r /opt/pycharm-2016.3.1/Copy the code
    1. Delete the hidden directory under the home directory that is used to save configuration information
$rm - r ~ /. PyCharm2016.3 /Copy the code

Jetbrains – PyCharm. Desktop in /usr/share/applications/ should also be deleted if PyCharm is no longer used

1.4. Drill multi-file projects

  • A development project is to develop software that specifically solves a complex business function
  • Typically, each project has a separate directory for all project-related files
  • inPyCharmIn order to make which onePythonTo execute a program, you must first pass itExecute by right mouse buttonthe
  • For beginners, in a project to set up more than one program can be executed, is very convenient, can facilitate the practice and test of different knowledge points
  • For commercial projects, there is usually only one Python source that can be executed directly within a project

2. Comment

  • The function of annotations is to use their familiar language to annotate some code in the program and enhance the readability of the program

2.1 Single Line Comment (Line comment)

  • In order to#At the beginning,#Everything on the right is treated as a caption, not the actual program to be executed, but as an auxiliary illustration
print("hello python")  # output 'Hello Python'
Copy the code

To ensure readability of the code, it is recommended to add a space after the # before writing the corresponding caption; To ensure readability, there should be at least two Spaces between comments and code.

2.2 Multi-line comments (block comments)

  • To use multi-line comments in Python programs, use a pair of three consecutive quotation marks (single and double quotation marks work)
""" This is a multi-line comment and in between multi-line comments you can write a lot of things... "" " 
print("hello python")
Copy the code

Tip:

  1. More comments are not always better, and you don’t need to add comments for self-explanatory code
  2. For complex operations, several lines of comment should be written before the operation begins
  3. For code that is not self-explanatory, add a comment at the end of the line (comments should be at least 2 Spaces away from the code for readability)
  4. Never describe the code. Assume the person reading the code knows Python better than you do. They just don’t know what your code does

2.3 Code Specification:

  • PythonA series of documents are available for Python Enhancement Proposals (PEP), of which the eighth document is dedicated toThe Python code formatGave advice, or as it’s commonly knownPEP 8:
    • The document address: www.python.org/dev/peps/pe…
    • Google has a corresponding Chinese document: useful – Google – styleguide. Readthedocs. IO/en/latest/g…

3. The operator

3.1 Arithmetic operators

Is a symbol used to perform basic arithmetic operations, to handle four operations, and “+” and “*” can be used to handle strings.

The operator describe The instance
+ add 10 plus 20 is 30
Reduction of 10 minus 20 is minus 10
* take 10 times 20 is 200
/ In addition to 10/20 = 0.5
// Take the divisible Returns the integer part of the division (quotient) 9 // 2 and outputs 4
% modulo Returns the remainder of the division 9%2 = 1
支那 power Also known as power, power, 2 ** 3 = 8

3.2 Comparison (relation) operators

The operator describe
= = Check whether the values of the two operandsequalIf so, the condition is True and returns True
! = Check whether the values of the two operandsNot equal to theIf so, the condition is True and returns True
> Check whether the value of the left-hand operandIs greater thanThe value of the right-hand operand, if True, returns True
< Check whether the value of the left-hand operandLess thanThe value of the right-hand operand, if True, returns True
> = Check whether the value of the left-hand operandGreater than or equal toThe value of the right-hand operand, if True, returns True
< = Check whether the value of the left-hand operandLess than or equal toThe value of the right-hand operand, if True, returns True
  • In Python 2.xIs not equal toYou can also use<>The operator
  • ! =The same is true in Python 2.xIs not equal to

3.3 Assignment operators

  • In Python, use=You can assign values to variables. When you do arithmetic, to simplify your code,PythonAlso provides a range of andArithmetic operatorThe correspondingThe assignment operator, pay attention to:Assignment operators cannot use Spaces between them.
The operator describe The instance
= A simple assignment operator C = a + b Assigns the result of a + b to c
+ = The addition assignment operator C plus a is the same thing as c is equal to c plus a
– = The subtraction assignment operator C minus a is the same thing as c minus a
* = Multiplication assignment operator C times a is the same thing as c times a
/ = The division assignment operator C/a is the same thing as c = c/a
/ / = Takes the divisible assignment operator C //= a is equivalent to c = c // a
% = takedie(remainder) assignment operator C %= a is the same thing as c = c % a
* * = Power assignment operator C **= a is the same thing as c = c ** A

3.4 Identity operators

The identity operator compares the memory location of two objects. There are two common identity operators, described below:

The operator describe The sample
is Determines whether two identifiers refer to the same object X is y, like id(x) == id(y)
is not Determine whether two identifiers refer to different objects X is not y, like id(a)! = id(b)

differentiate

  • Is is used to determine whether the object referenced by two variables is the same
  • == Is used to determine whether the values of the referenced variables are equal

3.5 Member operators

The Python member operator tests whether a given value is a member of a sequence. There are two member operators, described as follows:

The operator describe
in Returns true if the value of a variable is found in the specified sequence, false otherwise.
not in Returns true if the value of the variable cannot be found in the specified sequence, false otherwise.

3.6 Logical operators

The operator Logical expression describe
and x and y True is returned only if both x and y are True

Otherwise, return False whenever either x or y is False
or x or y Return True as long as either x or y is True

False is returned only if both x and y are False
not not x If x is True, return False

If x is False, return True

3.7 Operator priority

  • The following table is ranked from highest to lowest arithmetical priority:
The operator describe
支那 Power (highest priority)
% * / / / Multiply, divide, take the remainder, take the exact division
+ – Addition, subtraction
< = < > > = Comparison operator
= =! = Equal operator
= %= /= //= -= += *= **= The assignment operator
is is not Identity operator
in not in Member operator
not or and Logical operator

< complement > program execution principle

  1. The operating system first asks the CPU to copy the Python interpreter’s programs into memory
  2. The Python interpreter tells the CPU to translate the code in a Python program from the top down, based on syntax rules
  3. The CPU is responsible for executing the translated code

How big is the Python interpreter?

  • To view the size of the Python interpreter, run the following terminal command
# 1. Verify the interpreter location
$ which python

# 2. View python file sizes (just a soft link)
$ ls -lh /usr/bin/python

# 3. Check for specific file sizes$ls - lh/usr/bin/python2.7Copy the code

4. The variable

4.1 Definition of Variables

  • In Python, each variable must be assigned a value before it can be used, and then the variable can be created
  • Variables can be defined using the results of other variables
  • A variable name defines a variable only when it first appears
Variable name = valueCopy the code

In the interactive way, if you want to view the contents of a variable, you can directly enter the name of the variable. You do not need to use print function to run the interpreter. If you want to output the contents of the variable, you must use print function

4.2 Variable types

  • inPythonIs defined asYou do not need to specify the type(required in many other high-level languages), Python can be based on=The value to the right of the equal sign automatically deduces the type of data stored in the variable
  • Data types can be divided intoDigital typeThe digital type
    • Digital type
      • Integer (int) : All integers in Python3 are represented as long integers. Therefore, long integers have no separate numeric type.
      • Floating point (float)
      • The Boolean (bool) : I’mTrue Number of non-zero— Non-zero means true or falseFalse 0.
      • The plural (complex) : Complex numbers are real floating-point numbers of ordered pairs represented by x + yj, where x and y are real numbers and j is an imaginary unit.
    • Non-numeric: Some operators also support these data types. See 4.4.5.3 Operators.
      • String (str) : plus (+) is the string concatenation operator, asterisk (*) is the repeat operator.
      • List (list)
      • Tuples (tuple)
      • Dictionary (dict)

Tip: In Python 2.x, integers are also divided according to the length of the stored value:

  • int(integer)
  • long(Long integer)
  • usetypeFunction to view the type of a variable
In [1]: type(name)
Copy the code
< complement > Calculation between different types of variables
  1. Numerical variables can be computed directly between them
  • In Python, two numeric variables are directly arithmetical
  • If the variable isboolType, in the calculation
    • TrueThe corresponding number is theta1
    • FalseThe corresponding number is theta0
  1. String variableUsed between+Concatenated string
  2. String variableYou can andThe integeruse*Concatenate the same string repeatedly
  3. No other calculations can be made between numeric variables and strings
< complement > Gets input from the keyboard: input
  • This is available in PythoninputThe function waits for user input from the keyboard
  • Anything the user enters is considered a string by Python
String variable = input("Warning message:")
Copy the code
< complement > type conversion function
function instructions
int(x) Convert x to an integer
float(x) Convert x to a floating point number
str(x) Converts object X to a string representation
tuple(s) Convert s to a tuple
list(s) Convert s to a list
price = float(input("Please enter price :"))
Copy the code
< complement > format output: print
  • If you want to output both text information and data, you need to use formatting operators
  • %Referred to asFormatting operator, specifically for handling formatting in strings
    • contains%The string is calledFormatted string
    • %And differentcharacterEd),Different types of dataYou need to useDifferent formatting characters
Formatting character meaning
%s string
%d Signed decimal integer,%06dThe integer number of digits that represents the output, used where insufficient0completion
%f Floating point number,%.2fIndicates only two digits after the decimal point
% % The output%
  • The syntax is as follows:
print("Format string"% variable1)

print("Format string"% (variable1, the variable2...) )Copy the code

4.3 Naming variables

4.3.1 Identifiers and keywords

Identifiers are variable and function names defined by programmers

  • Identifiers can consist of letters, underscores, and numbers
  • You can’t start with a number
  • The name cannot be the same as the keyword

Keywords are identifiers that are already used inside Python

  • Keywords have special functions and meanings
  • Developers are not allowed to define identifiers with the same name as the keyword
  • To view the value, run the following commandPythonThe keyword in
In [1] :import keyword
In [2]: print(keyword.kwlist)
Copy the code
4.3.2 Naming rules for variables

The naming convention can be considered a convention and is not absolute or mandatory. The purpose is to increase code recognition and readability. Note that identifiers in Python are case sensitive

  1. When defining variables, to ensure that the code is formatted,=You should leave a space to the left and right of
  2. In Python, if a variable name needs to consist of two or more words, it can be named as follows: lowercase letters for each word, and between words_The underlineConnect, for example:first_name,last_name,qq_number,qq_password.

And, of course, there’s camelback nomenclature: Small camelback nomenclature: start the first word with a lowercase letter and capitalize the first letter of subsequent words, e.g. FirstName, lastName. Big CamelCase nomenclature, in which the first letter of each word is capitalized, e.g. FirstName, LastName, CamelCase.

4.4 Advanced variable types

In Python, all non-numeric variables support the following features: 1. Value [] 3. 4. Calculate length len, Max /min, compare, delete del 5. Link + and repeat * 6. Slice

4.4.1 List

  • List(List) YesPythonThe use ofThe most frequentIn other languages, it is usually calledAn array of, specifically for storageA bunch of information, the list with[]Definition,dataUsed between.Delimited, list ofThe index0Start.

The index is the location number of the data in the list. The index can also be called the subscript

name_list = ["zhangsan"."lisi"."wangwu"]
Copy the code

< complement >del keyword
  • usedelKeyword (deleteYou can also delete elements from the list
  • delKeywords are essentially used toTo remove a variable from memory
  • If you are usingdelThe keyword removes the variable from memory so that subsequent code can no longer use it
In [1]: l = [1.2.3.4]
In [2] :del l[1]
In [3]: l[1]
Out[3] :3
Copy the code

To remove data from a list in daily development, it is recommended to use the methods provided by the list

< complement > functions and methods
  • Functions encapsulate independent functions and can be called directly
Function name (parameter)Copy the code

Functions need to be memorized

  • Methods are similar to functions in that they encapsulate independent functionality
  • Methods need to be called on an object to represent operations to be performed on that object
Object. Method name (parameter)Copy the code

Typing. After a variable, and then choosing the operation to perform on that variable is much easier to remember than a function

< complement > loop through
  • Traversal is the process of retrieving data from the list from beginning to end, performing the same operation on each element within the body of the loop.

  • In Python, iterating over a list can be done using for to make it more efficient.

# list of variables in used inside the for loop
for name inName_list: inside the loop for the list elements print(name)Copy the code

  • Although Python lists can store different types of data
  • But in development, more application scenarios are
    1. Lists store the same type of data
    2. Within the body of the loop, the same action is performed for each element in the list by iterating through it

4.4.2 Tuple

  • TupleTuples are similar to lists except that of tuplesElements cannot be modified
    • A tuple represents a sequence of elements
    • tuplesPythonIn development, there are specific application scenarios
      • Used to storeA bunch of information.dataUsed between.separated
    • A tuple with(a)Defined, of tuplesThe index0To start,The indexThat’s where the data istuplesThe location number in.
info_tuple = ("zhangsan".18.1.75)
Copy the code

Create an empty tuple:

info_tuple = ()
Copy the code

When a tuple contains only one element, you need to add a comma after the element:

info_tuple = (50.)Copy the code

  • In Python, you can useforLoop over all non-numeric variables:The list of,tuples,The dictionaryAs well asstring
  • Tip: In real development, there isn’t much need to loop over tuples unless the data types in tuples can be identified
  • In development, more application scenarios are:
    • The arguments and return values of a function. A function can take any number of arguments or return more than one data at a time
    • Format string, formatted after the string(a)It’s essentially a tuple
    • Make the list unmodifiable to protect data security
Conversion between a < complement > tuple and a list
  • uselistThe tuple () function converts tuples to lists
The list (a tuple)Copy the code
  • usetupleThe tuple () function converts lists to tuples
The tuple (list)Copy the code

4.4.3 Dict

Dict is the most flexible data type in Python outside of lists. Dictionaries can also be used to store multiple pieces of data, often to store information about an object

  • Differences from lists:
    • A list is an ordered collection of objects
    • A dictionary is an unordered collection of objects
  • Dictionary use{}Definition.
  • Dictionary useKey/value pairStore data, used between key-value pairsThe comma .Space:
    • key keyIs the index
    • value valueIs the data
    • keyvalueUsed betweenThe colon :separated
    • The key has to be unique
    • Values can take any data type, but keys can only be strings, numbers, or tuples
xiaoming = {"name": "Xiao Ming"."age": 18."gender": True."height": 1.75}
Copy the code

  • Dictionary traversal is to get all key-value pairs from the dictionary in turn:
# for loop inside the 'key' variable 'in dictionary
for k in xiaoming:

    print("%s: %s" % (k, xiaoming[k]))
Copy the code

Tip: In real development, there is not much need for dictionary looping because each key/value pair in the dictionary holds different types of data

  • Although it can be usedfor intraverseThe dictionary
  • However, in development, more application scenarios are:
    • Use multiple key-value pairs to store information that describes an object — more complex data information
    • Put multiple dictionaries in a list and iterate, doing the same for each dictionary inside the body of the loop
card_list = [{"name": "Zhang"."qq": "12345"."phone": "110"},
             {"name": "Bill"."qq": "54321"."phone": "10086"}]Copy the code

4.4.4 String (STR)

  • A string is a string of characters, a data type that represents text in a programming language
  • This is available in PythonA pair of double quotes "orA pair of single quotes 'Define a string
    • Although it can be used\"or\ 'Do string escaping, but in real development:
      • If the string is needed internally", you can use'Defining strings
      • If the string is needed internally', you can use"Defining strings
  • You can use an index to get a character at a specified position in a string. The index count starts at 0
  • You can also usefor To iterate overEach character in a string

Most programming languages use “to define strings

string = "Hello Python"

for c in string:
    print(c)

Copy the code

Tip: There are enough built-in methods for manipulating strings in Python to give you more flexibility with strings at development time! Respond to more development needs!

1) Check type -9
methods instructions
string.isspace() Return True if string contains only Spaces
string.isalnum() Returns True if the string has at least one character and all characters are letters or numbers
string.isalpha() Returns True if the string has at least one character and all characters are letters
string.isdecimal() Returns True if string contains only numbers,The Angle of digital
string.isdigit() Returns True if string contains only numbers,The Angle of digital,(1),\u00b2
string.isnumeric() Returns True if string contains only numbers,The Angle of digital.Chinese character digital
string.istitle() Returns True if string is captioned (capitalizing the first letter of each word)
string.islower() Returns True if the string contains at least one case-sensitive character, and all of these characters are lowercase
string.isupper() Returns True if the string contains at least one case-sensitive character, and all of these characters are uppercase
2) Find and replace -7
methods instructions
string.startswith(str) Checks if the string begins with STR, and returns True if so
string.endswith(str) Checks if the string ends with STR, and returns True if so
string.find(str, start=0, end=len(string)) Checks whether STR is contained in string, if start and end specify a range, and returns the start index if, otherwise- 1
string.rfind(str, start=0, end=len(string)) Similar to find(), but starting from the right
string.index(str, start=0, end=len(string)) This is similar to the find() method, except that string will report an error if STR is not present
string.rindex(str, start=0, end=len(string)) Similar to index(), but starting on the right
string.replace(old_str, new_str, num=string.count(old)) Replace old_str in string with new_str, if num is specified, no more than num times
3) Case conversion – 5
methods instructions
string.capitalize() Capitalize the first character of the string
string.title() Capitalize each word of the string
string.lower() Converts all uppercase characters in string to lowercase
string.upper() Converts lowercase letters in string to uppercase letters
string.swapcase() Invert case in string
4) Text alignment – 3
methods instructions
string.ljust(width) Return a left-aligned string and fill it with Spaces to a new string of length width
string.rjust(width) Return a right-aligned string filled with Spaces to the new string of length width
string.center(width) Returns a centered string filled with Spaces to a new string of length width
5) Remove whitespace – 3
methods instructions
string.lstrip() Truncate the whitespace character to the left of the string
string.rstrip() Truncate whitespace at the right (end) of the string
string.strip() Truncate the whitespace on the left and right sides of the string
6) Split and join – 5
methods instructions
string.partition(str) Divide the string string into a 3-element tuple (before STR, STR, and after STR)
string.rpartition(str) Similar to partition(), but starting from the right
string.split(str=””, num) String is separated by STR. If num has a specified value, only num + 1 substrings are separated. STR defaults to ‘\r’, ‘\t’, ‘\n’ and Spaces
string.splitlines() Returns a list containing rows as elements, separated by rows (‘\r’, ‘\n’, ‘\r\n’)
string.join(seq) Combine all elements in SEq into a new string, using string as the delimiter
< fill > slice of string
  • sliceMethods are applicable tostring,The list of,tuples
    • Slicing uses index values to limit the range, cutting out small strings from a large string
    • Lists and tuples are ordered collections that can be retrieved by index values
    • A dictionary is an unordered collection that uses key-value pairs to hold data

String [Start index: End index: step]Copy the code

Note:

  1. The specified interval belongs toLeft closed right away[Start index, end index]= >Start index <= range < end index
    • fromThe startingBit start, goThe end of theThe first digit of the bitThe end (Does not contain the end bit itself)
  2. Starting from scratch, the opening index number can be omitted, but the colon cannot be omitted
  3. The end index number can be omitted and the colon cannot be omitted
  4. The default step is1, if the slice is continuous,Both numbers and colons can be omitted
Order and reverse order of < complement > indexes
  • Not only sequential indexing is supported in Python, but also reverse indexing is supported
  • An inverted index is one that evaluates an index from right to left: the rightmost index is -1, decreasing in order.
num_str = "0123456789"

# 1. Cut a string from position 2 to 5
print(num_str[2:6])

# 2. Cut the string from 2 to the end
print(num_str[2:])

# 3. Intercept the string from 'start' to 5
print(num_str[:6])

# 4. Intercept the full string
print(num_str[:])

# 5. Truncate the string every other character from the starting position
print(num_str[::2])

# 6. Start with index 1 and take each other
print(num_str[1::2])

# Reverse slice
# -1 indicates the last to last character
print(num_str[-1])

# 7. Cut the string from 2 to the end of -1
print(num_str[2:-1])

# 8. Intercept the last two characters of the string
print(num_str[-2:])

# 9. String inversions (interview questions)
print(num_str[::-1])
Copy the code

4.4.5 Advanced application of common methods and variables

4.4.5.1 Built-in functions

Python includes the following built-in functions:

function describe note
len(item) Count the number of elements in the container
del(item) To delete a variable Del comes in two ways
max(item) Returns the maximum number of elements in the container In the case of dictionaries, only key comparisons are performed
min(item) Returns the minimum value of the element in the container In the case of dictionaries, only key comparisons are performed
cmp(item1, item2) Compare two values, negative 1 is less than PI over 0 is equal to PI over 1 is greater than PI Python 3.x cancels the CMP function

Note: The string complies with the following rules: “0” < “A” < “A”.

4.4.5.2 slice
describe Python expression The results of Supported data types
slice “0123456789” [: : – 2] “97531” String, list, tuple
  • Slicing uses index values to limit the range, cutting out small strings from a large string
  • Lists and tuples are ordered collections that can be retrieved by index values
  • A dictionary is an unordered collection that uses key-value pairs to hold data
4.4.5.3 operator.
The operator Python expression The results of describe Supported data types
+ [1, 2] + [3, 4] [1, 2, 3, 4] merge String, list, tuple
* [“Hi!”] * 4 [‘Hi!’, ‘Hi!’, ‘Hi!’, ‘Hi!’] repeat String, list, tuple
in 3 in (1, 2, 3) True Does the element exist Strings, lists, tuples, dictionaries
not in 4 not in (1, 2, 3) True Whether the element does not exist Strings, lists, tuples, dictionaries
> >= == < <= (1, 2, 3) < (2, 2, 3) True Element is String, list, tuple

Pay attention to

  • inIn theThe dictionaryAnd when you do that, you determine thatThe keys of the dictionary
  • innot inReferred to asMember operator
4.4.5.4 Built-in Functions Complete for loop syntax
  • Complete in PythonThe for loopThe syntax is as follows:
forvariableinCollection: loop body codeelse: FailedbreakExit the loop, and when the loop ends, the code will be executedCopy the code

Application Scenarios:

  • When iterating through nested data types, such as a list containing multiple dictionaries
  • Requirement: Determine whether a specified value exists in a dictionary
    • If so, prompt and exit the loop
    • If not, expect a unified prompt after the whole loop ends
4.4.5.5 Variable Reference
  • Variables and data are stored in memory
  • Function arguments and return values are passed by reference in Python

In Python, variables and data are stored separately, and the data is stored in a location in memory. Variables hold the location of the data in memory, which is called a reference. Use the id() function to check the location of the data in the variable.

Note: If the variable is already defined, assigning a value to a variable essentially changes the reference to the data

  • The variable no longer refers to the previous data
  • The variable is changed to a reference to the newly assigned data

In Python, variable names are similar to post-it notes attached to data:

  • Define an integer variableaAnd assign the value to1
code graphic
a = 1
  • The variableaThe assignment for2
code graphic
a = 2
  • Define an integer variableb, and the variableaAssigns the value tob
code graphic
b = a

In Python, function arguments/return values are passed by reference

def test(num):

    print("-" * 50)
    print("The memory address of %d within the function is %x" % (num, id(num)))

    result = 100

    print("The memory address of the return value %d is %x" % (result, id(result)))
    print("-" * 50)

    return  result

a = 10
print("Memory address before calling function %x" % id(a))

r = test(a)

print("The memory address of the argument after calling the function is %x" % id(a))
print("The memory address of the return value after calling the function is %x" % id(r))

Copy the code

4.4.5.6 Mutable and immutable types
  • Immutable type. Data in memory cannot be modified:

    • Numeric typesint.bool.float.complex.long(2.x)
    • stringstr
    • tuplestuple
  • Mutable type, in which data in memory can be modified:

    • The list oflist
    • The dictionarydict

Note: Dictionary keys can only use immutable types of data

Pay attention to

  1. Mutable type data changes are implemented through methods
  2. If I assign a new value to a variable of variable type,References will change
    • The variable no longer refers to the previous data
    • The variable is changed to a reference to the newly assigned data
< complement > hash(hash)
  • There’s a name built into Python calledhash(o)Function: receives aImmutable typeAs the data ofparameter.returnIt turned out to be aThe integer.
  • The hashIt is a kind ofalgorithm, its function is to extract dataCharacteristic code (fingerprint).Same thinggetSame result.Different contentgetDifferent results.
  • In Python, set the dictionary’sKey/value pairWill be the first tokeyforhashHave you decided how to store the dictionary data in memory for conveniencesubsequentOperations on dictionaries:Add, delete, change, search: key-value pairskeyMust be immutable type data, key-value pairsvalueIt can be any type of data.
4.4.5.7 Local variables and global variables
  • Local variables are variables defined inside a function and can only be used inside a function; After the function is executed, local variables inside the function will be reclaimed by the system. Different functions can define local variables with the same name, but have no effect on each other. Local variables usually temporarily hold data that needs to be used inside a function.
  • A global variable is a variable defined outside a function (not inside a function) that can be used inside all functions.

Tip: in most other development languages, global variables are not recommended — the range of variables is too large to maintain!

Note: When a function is executed, it needs to handle variables:

  1. First check if there is a local variable with the specified name inside the function. If so, use it directly
  2. If not, check whether a global variable with the specified name exists outside the function. If so, use the global variable directly
  3. If not, program error!

Note: a function cannot modify a reference to a global variable directly. If it does, it must declare the variable as a global variable with global.

num = 10


def demo1(a):

    print("demo1" + "-" * 50)

    The # global keyword tells the Python interpreter that num is a global variable
    global num
    # define a local variable, do not change to a global variable, just the same variable name
    num = 100
    print(num)


def demo2(a):

    print("demo2" + "-" * 50)
    print(num)

demo1()
demo2()

print("over")
Copy the code

Note: In order to avoid confusion between local and global variables, some companies have some development requirements when defining global variables. For example, global variable names should be prefixed with g_ or gl_.

5. Judge (branch)

5.1 Syntax of the IF statement

1, if statement basic syntax:

ifConditions to judge: When the conditions are true, things to do...Copy the code

Note: Code is indented with a TAB key, or 4 Spaces — Spaces are recommended

  • Don’t mix tabs and Spaces in Python development!

2. If you need to do something without meeting the conditions, how do you do it?

ifConditions to judge: When the conditions are true, things to do...else: Things to do when conditions are not fixed...Copy the code
  • In program development, when judging conditions, it is usually necessary to judge multiple conditions at the same time. Only when multiple conditions are met, the subsequent code can be executed. At this time, logical operators are needed.
  • There are three logical operators in Python: and/or or/not
conditions1 andconditions2: If both conditions are met, returnTrueconditions1 orconditions2: Returns if either condition is metTrue
notCondition: No, noCopy the code

3, If you want to add more conditions, and different conditions need to execute different code, you can use elif:

ifconditions1Conditions:1Code that satisfies execution...elifconditions2Conditions:2When yes, the code executed......elifconditions3Conditions:3When yes, the code executed......elseWhen none of the above conditions are met, the code executed......Copy the code

Pay attention to

  • elifelseMust be andifUse in combination, not alone
  • Can beif,elifelseAnd their respective indented codes, as oneComplete code block

4, in the development, use if to determine the condition, if you want to increase the condition of the execution statement, you can use if nesting:

ifconditions1Conditions:1Code that satisfies execution...ifconditions1On the basis of conditions2Conditions:2When yes, the code executed......# Condition 2 is not met
    elseConditions:2If not, execute the code# Condition 1 is not met
elseConditions:1If not, the code executed......Copy the code

5.2 Application of the IF statement

5.2.1 Processing of random numbers
  • inPythonTo use random numbers, you first need to importThe random numberThe module— “Tool kit”
import random
Copy the code
  • After importing a module, you can directly type a. After the module name and then press Tab to prompt all functions contained in the module

  • Random.randint (a, b), returns an integer between [a, b], including a and b

  • Such as:

random.randint(12.20)  # generate random number n: 12 <= n <= 20
random.randint(20.20)  # The result is always 20
random.randint(20.10)  The lower limit must be less than the upper limit
Copy the code
5.2.2 Rock-paper-scissors
# Import the random tool package
# Note: When importing the toolkit, place the imported statements at the top of the file
Because it makes it easy for the code below to use the tools in the toolkit whenever needed
import random

# Input the punch to play from the console -- Rock (1)/Scissors (2)/Paper (3)
player = int(input("Please enter your punching stone (1)/scissors (2)/paper (3) :"))

# Random punches - assume that the computer can only throw stones to complete the overall code function
computer = random.randint(1, 3)

print("The fist chosen by the player is % D - the fist produced by the computer is % D." % (player, computer))

# Compare wins and losses
# 1 Rock beats scissors
# 2 Scissors beats paper
# 3 Cloth wins stone
# if (()
# or ()
# or ()):
if ((player == 1 and computer == 2)
        or (player == 2 and computer == 3)
        or (player == 3 and computer == 1)):

    print("Oh yeah, the computer is too weak!")
# draw
elif player == computer:
    print("Oh, that's a good one. Let's do it again.")
# Otherwise the computer wins
else:
    print("No, we'll fight till dawn!")
Copy the code

6. Cycle

6.1 Three processes of program execution

In program development, there are three processes:

  • Sequential – Execute code sequentially, from top to bottom
  • Branch – Decide which branch of code to execute based on criteria
  • Loop – Lets specific code execute repeatedly

6.2 Basic use of the while loop

Basic syntax for a while statement:

Initial conditions set - usually repeated counterswhileCondition (to determine whether the counter has reached the target number): What is done when the condition is met1Something to do when the conditions are met2Something to do when the conditions are met3. (omitted)... Processing condition (counter +1)
Copy the code

Because of the programmer’s reasons, forget to modify the judgment conditions of the loop inside the loop, resulting in continuous execution of the loop, the program will fall into an infinite loop and cannot be terminated!

Counter +1: You can simplify code writing with the assignment operator. There are two common counting methods, which can be called respectively:

  • Natural counting method(from1Start) — more in line with human habits
  • Procedure counting(from0Start) — almost all programming languages choose to count from zero

Therefore, when you write programs, you should try to get in the habit of counting loops starting at zero unless your requirements require it

6.3 break and continue

Break and continue are keywords that are specifically used in loops

  • break: When a condition is met, the loop exits and no further code is executed
  • continue: When a condition is met, the following code is not executed and the next loop is directly entered
  • breakcontinueOnly forCurrent loopeffective

6.4 While loop nesting

  • whileNesting is:whileThere are alsowhileAnd you have to finish one cycle per cycle.
whileconditions1: Something to do when conditions are met1Something to do when the conditions are met2Something to do when the conditions are met3. (omitted)...whileconditions2: Something to do when conditions are met1Something to do when the conditions are met2Something to do when the conditions are met3. (omitted)... Processing conditions2Processing conditions1
Copy the code

Example:

"" "print line 9: twinkle twinkle little star * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * "" "

# define the start line
row = 1

Print up to 9 lines
while row <= 9:
    Define the start column
    col = 1

    # Max print row column
    while col <= row:

        # end = "", no line breaks after output
        # "\t" outputs a TAB character on the console to assist in text alignment
        print("%d * %d = %d" % (col, row, row * col), end="\t")

        # number of columns + 1
        col += 1

    # one line of print finished line feed
    print("")

    # number of rows + 1
    row += 1

Copy the code
Escape character in < complement > string
  • \tPrint one on the consoletabsTo assist in output of textThe vertical directionMaintain alignment
  • \nPrint one on the consoleA newline

The function of tabs is to align text vertically by column without using a table

Escape character describe
\ \ Backslash notation
\ ‘ Single quotes
\” Double quotation marks
\n A newline
\t Horizontal tabs
\r enter

Function of 7.

7.1 Basic Use of Functions

The so-called function is to organize the code block with independent function into a small module, which can be called when needed. In the development of programs, the use of functions can improve the efficiency of writing and code reuse, the use of functions includes two steps: 1. Define functions – encapsulate independent functions. 2. Call functions – enjoy the fruits of encapsulation

  • Define a function:
defThe function name(a):Function wrapped code...Copy the code
  • Function call: PassThe function name ()Can complete the function call.

PyCharm debugging tool:

  • F8 Step Over can Step through code, treating function calls as if they were a line of code
  • F7 Step Into can Step through code and, if it is a function, inside it
  • Function documentation comments during development, if you want to add comments to a function, you should do so inDefine a functionBelow, useThree consecutive pairs of quotation marksIn theThree consecutive pairs of quotation marksWrite the description of the function between, inA function callLocation, use shortcut keysCTRL + QYou can view the description of the function.

Note: Because the function body is relatively independent, you should reserve two blank lines above the function definition and the rest of the code (including comments)

7.2 Function Parameters

7.2.1 Parameters and arguments

  • Fill in the parameters inside the parentheses following the function name, between multiple parametersThe comma .Space.
  • The parameters of the function, add the parameters of the functiongeneralityFor the same data processing logic, can adapt to more data ** :
    • Parameter: When defining a function, the arguments in parentheses are used to receive arguments and are used as variables inside the function.
    • Arguments: Arguments in parentheses used to pass data inside a function when it is called.
def sum_2_num(num1, num2):

    result = num1 + num2
    
    print("%d + %d = %d" % (num1, num2, result))

sum_2_num(50.20)

Copy the code

7.2.2 Variable and immutable parameters

Question 1: Does using an assignment statement for parameters inside a function affect the argument variables passed when the function is called? – not!

  • No matter what the parameters are passedvariableorimmutable
    • Whenever an assignment statement is used for a parameter, references to local variables are changed inside the function and references to external variables are not affected

Problem 2: If the argument passed is of mutable type, the contents of the data are changed inside the function using methods, which also affect the external data. For example, the += call to the list variable is essentially executing the extend method of the list variable.

7.2.2 Default Parameters

Definition function, can specify a default value to a parameter, with default values of parameters is known as the default, * the calling function, if there is no incoming the value of the default parameters are used inside the function definition function specifies the default values of parameters, the common parameters value is set to the default value, so as to simplify the function call. For example, sorting a list:

gl_num_list = [6.3.9]

Sort in ascending order by default, because this kind of application requires more
gl_num_list.sort()
print(gl_num_list)

The 'reverse' parameter needs to be passed only when descending sort is required
gl_num_list.sort(reverse=True)
print(gl_num_list)
Copy the code
  • Using an assignment statement after a parameter, you can specify a default value for the parameter
def print_info(name, gender=True):

    gender_text = "Boys"
    if not gender:
        gender_text = "Girls"

    print("% s is % s" % (name, gender_text))
Copy the code

prompt

  1. Default parameter, need to use the most common value as default value!
  2. If the value of a parameter cannot be determined, the default value should not be set. The specific value is passed from the outside when the function is called.

Pay attention to

  1. Must ensure that Default parameters with default values At the end of the argument list
  2. When you call a function with multiple arguments, you need to specify the parameter name so that the interpreter can know the relationship between the arguments!

7.2.3 Multi-valued Parameters

There may be times when there is an indeterminate number of arguments a function can handle. In this case, you can use multi-valued arguments.

  • pythonThere areTwo kinds ofMulti-valued parameter:
    • Added before parameter namea *You can receivetuples
    • Added before parameter nametwo 支那You can receiveThe dictionary
  • In general, when naming multi-valued parameters,habitUse the following two names
    • *argsDeposit —tuplesParameter, there’s one in front*
    • **kwargsDeposit —The dictionaryParameters, there are two in front支那
def demo(num, *args, **kwargs):

    print(num)
    print(args)
    print(kwargs)


demo(1.2.3.4.5, name="Xiao Ming", age=18, gender=True)
print("-"*20)
demo(1, (2.3.4.5), {"name":"Xiao Ming"."age":18."gender":True})
print("-"*20)
demo(1, (2.3.4.5), name="Xiao Ming", age=18, gender=True)

Copy the code

Unpacking of < complement > tuples and dictionaries
  • When calling a function with multi-valued arguments, if you want:
    • Will aTuples variablePass directly toargs
    • Will aThe dictionary variablePass directly tokwargs
  • You can use itunpacking, simplify the transmission of parameters,unpackingThe way is:
    • inBefore a tuple variable, an increase ofa *
    • inBefore dictionary variables, an increase oftwo *
def demo(*args, **kwargs):

    print(args)
    print(kwargs)

A tuple/dictionary variable needs to be passed to the corresponding argument of the function
gl_nums = (1.2.3)
gl_xiaoming = {"name": "Xiao Ming"."age": 18}

# pass num_tuple and xiaoming as tuples to args
# demo(gl_nums, gl_xiaoming)
demo(*gl_nums, **gl_xiaoming)

Copy the code

7.3 Return Value of a Function

  • Used in functionsreturnKeyword can return results, call function side, canUse the variablereceiveThe return result of the function.

Note: return means return, and subsequent code is not executed

def sum_2_num(num1, num2):
    """ sum of two numbers """

    return num1 + num2

Call the function and use the result variable to receive the computed result
result = sum_2_num(10.20)

print("Calculated %d" % result)

Copy the code

skills

  • inPython, you canPut a tupleuseAssignment statementAnd assign toMultiple variables
  • Note: The number of variables needs to be the same as the number of elements in the tuple
Use tuples to exchange the values of two variables
a, b = b, a
Copy the code

7.4 Nested calls to functions

  • A nested call is a function that calls another function within a function.
def test1(a):

    print("*" * 50)
    print("test 1")
    print("*" * 50)


def test2(a):

    print("-" * 50)
    print("test 2")
    
    test1()
    
    print("-" * 50)

test2()

Copy the code

Tip: in view of the changes in the work requirements, we should think calmly, do not easily modify the function that has been completed before and can be executed normally!

7.5 Recursion of functions

The programming trick of calling a function itself is called recursion

Features: A function calls itself internally

Code features:

  1. The code inside the function is the same, but the result is different for different arguments
  2. When a parameter satisfies a condition, the function is no longer executed, often referred to as the exit of recursion, otherwise an infinite loop occurs!

Example — Calculate the sum of numbers:

Requirements:

  1. Define a functionsum_numbers
  2. Be able to receive anumInteger parameter of
  3. Calculate 1 + 2 +… The results of the num
def sum_numbers(num):

    if num == 1:
        return 1
    
    # assume sum_numbers can add num-1
    temp = sum_numbers(num - 1)

    The core algorithm inside the function is the addition of two numbers
    return num + temp

print(sum_numbers(2))

Copy the code

7.6 Define functions in modules

Modules are a core concept of Python program architecture

A module is like a toolkit. To use the tools in the toolkit, you need to import the module import. Every Python source file ending with the extension py is a module, and global variables and functions defined in the module are tools that the module can provide to the outside world.

  • You can define variables or functions in a Python file
  • Then, inIn another fileuseimportImport this module
  • Once imported, it is ready to useModule name. Variable / Module name. functionUsing a variable or function defined in this module

Modules make it easy to reuse code you’ve written! The module name is also an identifier, and you cannot import the module in PyCharm if you start it with a number when naming Python files.

< fill > Pyc file

C is compiled.

  • Browse the program directory and you’ll find one__pycache__The directory.
  • There will be one in the directoryCpython-35.pyc hM_10_ separator moduleFile,cpython-35saidPythonVersion of the interpreter.
  • thispycFiles are created by the Python interpreterModule source codeconvertThe bytecode.

Python stores the bytecode this way as an optimization for startup speed.

  • What is bytecode?
  • PythonThe interpretation of the source program is divided into two steps:
    1. The source code is first processed and compiled to produce a binary bytecode.
    2. The bytecode is then processed to generate machine code that the CPU can recognize.
  • Once you have the module’s bytecode file, the next time you run the program, Python will load the.pyc file and skip compiling if the source code has not been modified since the last bytecode saving.
  • whenPythonWhen recompiling, it automatically checks the timestamps of the source and bytecode files.
  • If you modify the source code again, the bytecode will be recreated automatically the next time the program runs.

8. Files, exceptions, modules and packages

8.1 file

8.1.1 Concept of files

  • A computer file is a piece of data stored on some kind of long-term storage device
  • Long-term storage devices include hard disks, USB flash disks, portable disks, and cd-RoMs.

In a computer, a file is a text file stored on disk in binary format: it can be viewed using text editing software and is essentially a binary file: The saved content is not for people to read directly, but for other software to use, such as: image files, audio files, video files, etc. Binary files cannot be viewed with text editing software

8.1.2 Basic File operations

The procedure for manipulating a file: The procedure for manipulating a file in a computer is very fixed and consists of three steps:

  1. Open the file
  2. Read and write files
    • Read Reads the contents of a file into memory
    • Write Writes the contents of memory to a file
  3. Close the file

To manipulate files in Python, you need to remember 1 function and 3 methods

The serial number Function/method instructions
01 open Open the file and return the file action object
02 read Read the contents of the file into memory
03 write Writes the specified content to a file
04 close Close the file

The open function opens the file and returns the file object through which the read/write/close methods are called

Reading a file example

The first argument to the open function is the file name to open (the file name is case sensitive). If the file exists, the file action object is returned. If the file does not exist, an exception is thrown

The read method reads in and returns the entire contents of a file at once

The close method is responsible for closing a file. If you forget to close a file, system resources will be consumed and subsequent file access will be affected

Note: The read method moves the file pointer to the end of the file

# 1\. Open - File names need to be case sensitive
file = open("README")

# 2 \. Read
text = file.read()
print(text)

# 3 \. Closed
file.close()

Copy the code

prompt

  • In development, you usually write the open and close code first, and then write the read/write operations to the file in the middle!
< complement > file pointer
  • The file pointer marks where to start reading data
  • When a file is opened for the first time, the file pointer usually points to the beginning of the file
  • When performing thereadMethods after,The file pointerWill move toRead the end of the content
    • By default, it moves to the end of the file

Consider: If you execute the read method once and read everything, will you still get the content if you call the read method again? Answer: No! After the first read, the file pointer moves to the end of the file, and the next call does not read anything.

< fill > how to open a file
  • openFunction defaults toA read-onlyOpen the file and return the file object
f = open("File name"."Access Mode")
Copy the code
access instructions
r In order toread-onlyMethod to open a file. The pointer to the file will be placed at the beginning of the file, which isThe default mode. If the file does not exist, an exception is thrown
w In order toJust writeMethod to open a file. The file will be overwritten if it exists. If the file does not exist, create a new file
a In order toadditionalMethod to open a file. If the file already exists, the file pointer will be placed at the end of the file. If the file does not exist, create a new file to write to
r+ In order toRead and writeMethod to open a file. The pointer to the file will be placed at the beginning of the file. If the file does not exist, an exception is thrown
w+ In order toRead and writeMethod to open a file. The file will be overwritten if it exists. If the file does not exist, create a new file
a+ In order toRead and writeMethod to open a file. If the file already exists, the file pointer will be placed at the end of the file. If the file does not exist, create a new file to write to

Tip: Frequently moving the file pointer will affect the efficiency of reading and writing files. In the development, more files will be operated in read-only and write-only mode

Write file example

# Open file
f = open("README"."w")

f.write("Hello python! \n")
f.write("It's a beautiful day.")

# close file
f.close()

Copy the code
< fill > read file contents by line:readline()
  • readMethod will place the file by defaultAll content Read memory at one time
  • If the file is too large, it can be very heavy on memory
  • readlineMethod can read one line at a time
  • Method moves the file pointer to the next line, ready to read again

Correct posture for reading large files

# Open file
file = open("README")

while True:
    Read a line of content
    text = file.readline()

    # Determine if you have read the content
    if not text:
        break

    There is already a '\n' at the end of each read line
    print(text, end="")

# close file
file.close()

Copy the code

Copying large files

  • Open an existing file, read the contents line by line, and write sequentially to another file
# 1\. Open file
file_read = open("README")
file_write = open("The README [copy]"."w")

# 2\. Reads and writes files
while True:
    Read one line at a time
    text = file_read.readline()

    # check whether the content is read
    if not text:
        break

    file_write.write(text)

# 3\. Close file
file_read.close()
file_write.close()

Copy the code

8.1.3 Common File/Directory Management Operations

  • interminal / File browser, can perform the conventionalfile / directoryAdministrative actions, such as:
    • Create, rename, delete, change paths, view directory contents,…
  • In Python, if you want to implement these functions programmatically, you need to import themosThe module

File Management Operations

The serial number The method name instructions The sample
01 rename Rename file Os.rename (source file name, destination file name)
02 remove Delete the file Os.remove (file name)

Directory Management Operations

The serial number The method name instructions The sample
01 listdir Directory listing Os.listdir (Directory name)
02 mkdir Create a directory Os.mkdir (directory name)
03 rmdir Delete the directory Os.rmdir (directory name)
04 getcwd Get the current directory os.getcwd()
05 chdir Modifying the Working directory Os.chdir (Target directory)
06 path.isdir Check whether it is a file Os.path. isdir(File path)

Tip: Both relative and absolute paths are supported for file or directory operations

8.1.4 Encoding format of text files

  • Text files store content based onA character encodingFile, common encoding hasASCIICoding,UNICODECoding etc.

X uses THE ASCII encoding by default. Python 3.x uses the UTF-8 encoding by default

ASCIIcoding

  • The only thing on the computer256ASCIIcharacter
  • aASCIIThe memory is occupied1 byteThe space of
    • 80/1The permutation and combination of256Seed, that is2 * * 8

UTF-8Coding format

  • For use in computers1 ~ 6 bytesTo represent aUTF-8Character, covered byAlmost every region on earth
  • Most Chinese characters are represented by three bytes
  • UTF-8UNICODEAn encoding format for encoding

How to use Chinese in Ptyhon 2.x?

  • In Python 2.x filesThe first lineAdd the code# *-* coding:utf8 *-*, the interpreter will start withutf-8Code to process Python files, which is officially recommended!
  • You can also use# coding=utf8.

How do I traverse Unicode strings correctly in Python 2.x?

  • In Python 2.x, even if files are specifiedUTF-8Encoding format, but still when iterating through the stringTraversal in bytesstring
  • To be able to traverse the string correctly,When defining a string.Before the string quotes, add a lowercase letteruTell the interpreter that this is aunicodeString (usingUTF-8Encoded string)
# *-* coding:utf8 *-*

# Before the string, add a 'u' to indicate that the string is a UTF8 string
hello_str = uHello world.

print(hello_str)

for c in hello_str:
    print(c)

Copy the code

8.2 abnormal

8.2.1 Concepts of exceptions

  • When the program runs, ifThe Python interpreter encounterTo a mistake,Stops the execution of the program and prompts some error messagesAnd this isabnormal
  • The action of a program stopping execution with an error message is usually called raising an exception

During the program development, it is difficult to deal with all the special cases in all aspects. Through the exception capture, we can deal with the emergencies centrally, so as to ensure the stability and robustness of the program

8.2.2 Catching exceptions:try except else finally

Simple catch exception syntax

  • In program development, ifExecution of some code is not certain to be correct, can be increasedTry (try)Catch exceptions
Try: code that is tried except: error handlingCopy the code
  • try try, below write code to try, not sure if it will work
  • except If it is notBelow, write the code for failed attempts

Simple exception catch 1 – requires the user to enter an integer

try:
    Prompt the user for a number
    num = int(input("Please enter a number:"))
except:
    print("Please enter the correct number")

Copy the code

Error type capture

  • During program execution, different types of exceptions may be encountered and different responses need to be made for different types of exceptions. In this case, you need to catch the error type
try:
    # Try to execute the codePass except Error type 1:# Code handling for error type 1Pass except (error type 2, error type 3):# Code handling for error types 2 and 3
    pass
except Exception as result:
    print("Unknown error %s" % result)
Copy the code
  • whenPythonThe interpreterAn exception is thrownWhen,The first word of the error message on the last line is the error type

Exception Type capture 2 — requires the user to enter an integer

try:
    num = int(input("Please enter an integer:"))
    result = 8 / num
    print(result)
except ValueError:
    print("Please enter the correct integer")
except ZeroDivisionError:
    print("Error dividing by zero")
Copy the code

Catching unknown errors

  • It is difficult to anticipate all possible errors during development
  • If you want the programNo matter what goes wrongNot because ofPythonThe interpreterAn exception is thrown and terminatedYou can add another oneexcept

The syntax is as follows:

except Exception as result:
    print("Unknown error %s" % result)
Copy the code

Complete syntax for exception capture

  • In real development, to be able to handle complex exception cases, the complete exception syntax is as follows:
try:
    # Try to execute the codePass except Error type 1:# Code handling for error type 1Pass except Error type 2:# For error type 2, the corresponding code handlingPass except (error type 3, error type 4):# Code handling for error types 3 and 4
    pass
except Exception as result:
    # Print error information
    print(result)
else:
    # Code that will execute if there is no exception
    pass
finally:
    # Code that executes regardless of exceptions
    print("Code that will execute regardless of exceptions.")

Copy the code
  • Else Code that executes only if there are no exceptions

  • Finally Code that executes regardless of exceptions

  • The complete exception catching code from the previous walkthrough looks like this:

try:
    num = int(input("Please enter an integer:"))
    result = 8 / num
    print(result)
except ValueError:
    print("Please enter the correct integer")
except ZeroDivisionError:
    print("Error dividing by zero")
except Exception as result:
    print("Unknown error %s" % result)
else:
    print("Normal execution")
finally:
    print("Execution complete, but not guaranteed.")

Copy the code

8.2.3 Abnormal transmission

  • Exception passing – When a function/method execution fails, the exception is passed to the caller of the function/method
  • If passed to the main program, there is still no exception handling, the program is terminated

Tip:

  • In development, you can add exception catching to the main function, and any other function called in the main function will be passed to the main function whenever an exception occurs
  • This eliminates the need to add a lot of exception catching to your code and keeps your code clean
' '1. Define the function 'demo1()' ** to prompt the user for an integer and return ** 2. Define the function 'demo2()' and call 'demo1()' 3. Call 'demo2()' in the main program' '
def demo1():
    return int(input(Please enter an integer:))

def demo2():
    return demo1()

try:
    print(demo2())
except ValueError:
    print("Please enter the correct integer")
except Exception as result:
    print("Unknown error %s" % result)

Copy the code

8.2.4 Throwing an Exception:raise

Application scenarios

  • In development, in addition toCode execution error PythonThe interpreter willthrowBesides the abnormal
  • You can also actively throw exceptions based on application-specific business requirements

The sample

  • Prompt the userEnter the passwordIf theLength less than 8Thrown,abnormal

An exception is thrown

  • PythonOne is provided inException Exception class
  • At development time, if meetSpecific business requirements, in the hope thatAn exception is thrownBy theOther functions that need to be handled catch exceptions, you can:
    1. createaExceptionobject
    2. useraise The keywordthrowThe exception object
' ''** Requirements ** * define the' input_password 'function to prompt the user for a password * If the user enters length < 8, throw an exception * If the user enters length >=8, return the password entered'' '
def input_password():

    Prompt the user for a password
    pwd = input("Please enter your password:")

    # 2\. Determine the password length, if the length >= 8, return the password entered by the user
    if len(pwd) > = 8:return pwd

    # 3\. Password length is insufficient, need to throw an exception
    # 1> Create exception object - use the exception's error message string as an argument
    ex = Exception("Password length not enough")

    # 2> Throw an exception object
    raise ex

try:
    user_pwd = input_password()
    print(user_pwd)
except Exception as result:
    print("Error found: %s" % result)

Copy the code

8.3 Modules and Packages

8.3.1 module

Modules are a core concept of Python program architecture

  • Each with an extensionpyAt the end of thePythonSource code files are all oneThe module
  • The module name is also an identifier and must comply with the naming rules of identifiers
  • Global variables, functions, and classes defined in a module are tools provided for direct use by the outside world
  • A module is like a toolkit. In order to use the tools in the toolkit, you need to import the module

Two ways to import modules

1) Import

Import module name 1, module name 2Copy the code

Tip: When importing modules, each import should have a single line

Import Module name 1 Import module name 2Copy the code
  • After the import
    • throughThe module name.useTools provided by the moduleThe global variable,function,class
  • useasSpecifies the alias of the module

If the module name is too long, you can use as to specify the module name for easy use in your code

Import Module name 1 AS module aliasCopy the code

Note: Module aliases should conform to the big camel name

2) the from… The import import

  • If you want toFrom a moduleIn the importPart of theTools can be usedfrom ... importThe way of
  • The import module nameA one-timeThe moduleAll tools are importedAnd throughModule name/aliasaccess
Import a tool from a moduleFrom module name 1 import tool nameCopy the code
  • After the import
    • You can use the tools provided by the module directly — global variables, functions, classes

Pay attention to

If two modules have a function of the same name, the function imported after the module overwrites the function imported before

  • Development timeimportThe code should be uniformly written inTop of code, it is easier to detect conflicts in time
  • Can be used once a conflict is foundasThe keywordGive one of the tools an alias
  • from... import *
Import all tools from the moduleFrom module name 1 import *Copy the code

Pay attention to

This method is not recommended, because the function name does not have any hint, problems are not easy to troubleshoot

< complement > the search order of modules

When importing a module, the Python interpreter:

  1. Search the current directory for the specified module name file, if there is directly imported
  2. If not, search the system directory again

During development, give the file a name, not the same as the system module file

Every module in Python has a built-in attribute __file__ to view the full path to the module

Principle – Every file should be imported

  • A single Python file is a module
  • When importing a file, all code in the file without any indentation is executed!

Actual development scenario

  • In the actual development, each module is independently developed, most of them are responsible for
  • The developerUsually inThe module below Add some test code
    • Used only within modules and not required to be imported into other files

__name__attribute

  • __name__Property to do so, test the module’s codeRun only under test conditions, and inIs not executed when imported!
  • __name__PythonA built-in property of thestring
  • ifIt was imported by another file.__name__isModule name
  • ifIs the currently executing program __name____main__

In many Python files you’ll see code in the following format:

# import module
Define global variables
# define classes
# define function

# at the bottom of the code
def main():
    #...
    pass

# Determine whether to execute the following code based on __name__
if __name__ == "__main__":
    main()

Copy the code

8.3.2 Package

  • A package is a special directory containing multiple modules
  • There is one in the directorySpecial file __init__.py
  • The package namenamingSame as the variable name,Lowercase letters + _

Benefits: Using the import package name allows you to import all modules in a package at once

case

  1. Create a newhm_messagepackage
  2. In the directory, create two new filessend_messagereceive_message
  3. insend_messageDefine one in the filesendfunction
  4. inreceive_messageDefine one in the filereceivefunction
  5. Import directly from the outsidehm_messageThe package

__init__.py

  • It has to be used outsidepackageThe module in the__init__.pySpecified in theList of modules available to the outside world
Import the list of modules from the current directory
from . import send_message
from . import receive_message
Copy the code

8.3.3 Publishing modules

  • If you want to share your modules with others, follow these steps:
  1. Create the setup. Py
  • setup.pyThe file
from distutils.core import setup

setup(name="hm_message".# the package name
      version="1.0".# version
      description="Itheima's Send and receive message module".# Description
      long_description="Complete sending and receiving message module".# Complete description
      author="itheima".# the author
      author_email="[email protected]".# Author email
      url="www.itheima.com".# home page
      py_modules=["hm_message.send_message"."hm_message.receive_message"])

Copy the code

Detailed information about the dictionary parameters, can refer to the official website: docs.python.org/2/distutils…

  1. Building blocks
$ python3 setup.py build
Copy the code
  1. Generate and publish compressed packages
$ python3 setup.py sdist
Copy the code

Note: whichever version of the module you want to make, use the same version of the interpreter!

4) Install the module

$tar -zxvf hm_message-1.0.tar.gz $sudo python3 setup.py installCopy the code

5) Uninstall the module

Delete the module installation directory directly from the installation directory

$ cd /usr/local/lib/python3.5/dist-packages/ $sudo rm -r hm_message*Copy the code

pipInstalling third-party Modules

  • Third-party modulesUsually means byWell-known third party team The development ofAnd beWidely used by programmersPythonPackages/modules
    • For example,pygameIt’s a very mature setGame development module
  • pipIt’s a modern, universal onePythonPackage management tool
  • Provides forPythonPackage search, download, install, uninstall and other functions

The installation and uninstallation commands are as follows:

Install the module into the Python 2.x environment
$ sudo pip install pygame
$ sudo pip uninstall pygame

Install the module into the Python 3.x environment
$ sudo pip3 install pygame
$ sudo pip3 uninstall pygame
Copy the code


The second part is object oriented

1. Object Oriented (OOP) basic concepts

Object Oriented Programming – OOP

    1. Process oriented – How? According to the development requirements, some functionally independent code is packaged into one function after another. Finally completed code is to call different function features sequentially: If the requirements are complex, the code will become very complex. If there is no set formula, it will be very difficult to develop a complex project!
    1. Object oriented – Who will do it?

      Compared to functions, object orientation is more encapsulation, encapsulating multiple methods within an object based on responsibility

      Before completing a requirement, define responsibilities — things to do (methods) Determine different objects according to responsibilities, encapsulate different methods (multiple) inside the object, and finally complete the code, which is to have different objects call different method characteristics in sequence: It pays attention to objects and responsibilities. Different objects assume different responsibilities, which is more suitable for dealing with complex demand changes. It is specialized in dealing with complex project development

    1. Classes and objectsclassIs for a group of peopleThe sameA general term for something that is characteristic or behavior, which is abstract, characteristic is calledattributeThe behavior is calledmethods.objectIs a concrete being created by a class, an instantiation of a class. In program development, to design a class, there are usually three elements:
      • The name of such a thing that satisfies the great hump nomenclature
      • What are the characteristics of things like attributes
      • What kind of behavior do things like methods have

2. Object-oriented basic syntax

2.1 DIR Built-in functions and methods

Objects are almost everywhere in Python, and the variables, data, and functions we studied earlier are all objects. There are two ways to verify in Python:

  • inIdentifier/dataEnter a dot after.And then pressTABKey, iPython prompts for a list of methods that the object can call.
  • Using built-in functionsdirThe incomingIdentifier/data, you can view theAll properties and methods. prompt__ The method name __The formatting method is provided by PythonBuilt-in methods/properties.
The serial number The method name type role
01 __new__ methods Create an objectIs automatically called
02 __init__ methods The object is initializedIs automatically called
03 __del__ methods Before an object is destroyed from memoryIs automatically called
04 __str__ methods Returns a description of the object, print function output use

Tip Using the dir() function saves a lot of learning from rote memorization.

2.2 Defining a simple class (containing only methods)

Object orientation is more encapsulation, encapsulating multiple methods in a class so that objects created from that class can call those methods directly!

Define a class that contains only methods:

classThe name of the class:

    defMethod 1(self, argument list):
        pass
    
    defMethod 2(self, argument list):
        pass
Copy the code

The method is defined in much the same format as the functions we learned before, except that the first argument must be self. Note: Class names should be named according to the big camel name. When a class definition is complete, to create an object using that class, the syntax is as follows:

Object variable = class name ()Copy the code

In object-oriented development, the concept of references is equally applicable!

Use print to print an object variable. By default, print which class created the object referenced by the variable and its address in memory (in hexadecimal notation).

Tip: In computers, memory addresses are usually represented in hexadecimal notation.

If you want to print a custom object variable using print during development, you can use the __str__ built-in method:

class Cat:

    def __init__(self, new_name):

        self.name = new_name

        print("% s" % self.name)

    def __del__(self):

        print(Go to "% s" % self.name)

    def __str__(self):
        return "I am a kitten: % S" % self.name

tom = Cat("Tom")
print(tom)
Copy the code

Note: the __str__ method must return a string.

2.3 The self argument in the method

In Python, assigning attributes to objects is very easy, just by passing them through code outside the class. Setting a property is fine, but not recommended:

class Cat:
    """ This is a cat. """

    def eat(self):
        print("Kittens love fish.")

    def drink(self):
        print("The kitten is drinking water.")

tom = Cat()
# Set attributes for the object
tom.name = "Tom"

Copy the code

Because: object attributes should be encapsulated inside the class

The self inside the method is a reference to which object calls the method

  • Inside the method encapsulated by the class,selfRepresents the object that is currently calling the method itself, inside the method: can passself.To access properties of objects, you can also passself.Call other methods of the object.
  • When calling a method, the programmer does not need to pass the self argument.
  • Outside the class, passThe variable name.Access objects’ properties and methods in class-encapsulated methods, throughself.Access the properties and methods of an object

2.4 Initialization Method:__init__

  • When usingThe name of the class ()When an object is created, the following operations are automatically performedSpace allocated in memory— Creates objects as objectsProperty sets the initial value— Initialization method (__init__)

The __init__ method is specifically used to define which properties a class has!

  • A property is defined by using self. property name = the initial value of the property inside the __init__ method. After the property is defined, objects created using the class will have the property.

  • In development, if you want to set the attributes of an object at the same time as the object is created, you can modify the __init__ method:

    1. Define the property value that you want to set as__init__Method parameters
    2. Used within a methodSelf. property = parameterReceives externally passed parameters
    3. When creating an object, use theClass name (Attribute 1, attribute 2...)call
class Cat:

    def __init__(self, name):
        print("Initialize method %s" % name)
        self.name = name
    ...
    
tom = Cat("Tom")... lazy_cat = Cat("Big Lazy Cat")...Copy the code

2.5 Private Properties and private methods

Application scenarios

  • In real development, some properties or methods of an object may be intended to be used only inside the object, but not accessed externally
  • A private property is a property that an object does not want to make public
  • Private methods are methods that an object does not want to be exposed

Define the way

  • When defining a property or method, add two underscores to the property or method name to define a private property or method:

In Python, there is no real private property or method. When you name an attribute or method, you do something special to make it invisible to the outside world: prefix the name with _ class name => _ class name __

# private property, not directly accessible externally
print(xiaofang._Women__age)

# private method, external cannot call directly
xiaofang._Women__secret()
Copy the code

Tip: In everyday development, do not use this method to access private properties or methods of objects.

3. Encapsulation, inheritance and polymorphism

Three features of object orientation:

  1. Encapsulate properties and methods into an abstract class based on responsibilities
  2. Inheritance enables the reuse of code. The same code does not need to be written repeatedly
  3. Polymorphic objects call the same method, resulting in different execution results, increasing the flexibility of the code

3.1 inheritance

3.1.1 single inheritance

The concept of inheritance: a subclass owns a parent class and all properties and methods encapsulated in its parent class.

classThe name of the class(Parent class name):

    pass
Copy the code

Override override override override override override override override override override override override override override override override override override override

  1. Overriding methods of the parent class: the method implementation of the parent class is completely different from the method implementation of the child class. It is equivalent to defining a method with the same name as the parent class and implementing it.
  2. On the superclass methodextensionThe method implementation of a subclass that contains the parent class overrides the parent class method in the subclass. Use it where neededSuper (). Superclass methodTo call the parent method’s execution code; Other places write subclass-specific code implementations for the needs of subclasses.
About super
  • In PythonsuperIs a special class
  • super()Is the use ofSuper classThe created object
  • The most commonly used scenario is to call the method implementation encapsulated in the parent class when overriding a parent class method

Another way to call a superclass method: In Python 2.x, if you need to call a superclass method, you can also use the following method: superclass name. Method (self). This is currently supported in Python 3.x, but is not recommended because the name of the class where the method is called also needs to be changed if the parent class changes.

Private attributes and private methods of the parent class

A subclass object cannot access its parent’s private properties or methods directly within its own methods. A subclass object can access its parent’s private properties or methods indirectly through its parent’s public methods

  • Private properties and methods are the privacy of the object. They are not public and cannot be directly accessed by the outside world or subclasses
  • Private properties and methods are often used to do internal things

3.1.2 multiple inheritance

Subclasses can have more than one parent class and have all the attributes and methods of the parent class. For example, children inherit the characteristics of their parents.

classA subclass of(parent class name1The parent class name2...):
    pass
Copy the code
MRO in Python (Method Resolution Order)
  • If a method of the same name exists in a different parent class, which parent class does the subclass object call when it calls a method? Tip: Try to avoid this confusion when developing! Avoid multiple inheritance if there are attributes or methods with the same name between parent classes.
  • Python provides a built-in property for classes__mro__You can view the method search order
    • When searching for methods, the mrO output is searched from left to right
    • If a method is found in the current class, it is executed without searching
    • If it does not, it looks for a corresponding method in the next class. If it does, it does not search
    • If the last class is found and no method is found, the program reports an error

MRO is method Resolution Order (MRO). MRO is a method resolution order (MRO). MRO is a method resolution order (MRO)

New and old (classic) classes
  • New type: toobjectIs a base class, recommended
  • Classic: NoobjectIs a base class, not recommended

When you define a class in Python 3.x, if you do not specify a parent class, object is used as the base class by default. Object is not used as the base class.

  • To make sure you write code that runs in Both Python 2.x and Python 3.x! When defining a class in the future, if there is no parent class, it is recommended to inherit from object:
classThe name of the class(object):
    pass
Copy the code

Object is Python’s base class for all objects, with built-in properties and methods that can be viewed using the dir(object) function.

3.2 polymorphic

Three features of object orientation:

  1. Encapsulate properties and methods into an abstract class based on responsibilities
    • Criteria for defining classes
  2. Inheritance enables the reuse of code. The same code does not need to be written repeatedly
    • Tips for designing classes
    • Subclasses write specific code for their own specific needs
  3. Polymorphic subclass objects call the same superclass method, producing different execution results
    • Increase the flexibility of your code
    • The premise is to inherit and override the parent class methods
    • The technique of calling a method does not affect the internal design of a class

Polymorphism makes it easier to write common code and make common programming to adapt to changing requirements!

Case: Encapsulate the method game in the Dog class: ordinary Dog is just a simple play definition. XiaoTianDog inherits from Dog and rewrites the game method: Crouching Dog needs to play in the sky. Define the Person class and encapsulate a method to play with dogs: Inside the method, let the dog object call the Game method directly

Class attributes and class methods

4.1 Class structure

Usually put: The object that you create is called an instance of the class and the action that you take to create it is called instantiating properties of the object is called instance properties and the methods that the object calls are called instance methods and each object has its own memory space that holds its own properties and the methods of multiple objects are only one copy in memory, and when you call a method, A reference to an object needs to be passed inside the method

In Python, a class is a special object.

Everything is an object in Python:

  • Class AAA: Defined classes belong to class objects
  • Obj1 = AAA() belongs to the instance object

When the program is running, the class is also loaded into memory. When the program is running, there is only one copy of a class object in memory, and you can create many instances of an object using a class. In addition to encapsulating the properties and methods of the instance, a class object can also have its own properties and methods — class properties, class methods, by class name. Can access a class’s properties or call a class’s methods

4.2 Class attributes and instance Attributes

Class attributes are attributes defined in a class object that are usually used to record characteristics associated with that class. Class attributes are not used to record characteristics of specific objects. Example: Define a utility class, each tool has its own name.

class Tool(object):

    Use the assignment statement to define class attributes and record the total number of tool objects created
    count = 0

    def __init__(self, name):
        self.name = name

        # count +1 for class attributes
        Tool.count += 1


Create a tool object
tool1 = Tool("Axe")
tool2 = Tool("Hammer")
tool3 = Tool("Shovel")

How many objects were created using the Tool class?
print("Now % D tools have been created" % Tool.count)
Copy the code
Property acquisition mechanism

There is a look-up mechanism for getting attributes in Python

Therefore, there are two ways to access class attributes:

  • Class name. Class attribute
  • Object. Class attributes(Not recommended because if usedObject. Class property = valueThe assignment statement, it justAdd a property to the objectAnd theThe value of the class attribute is not affected)

4.3 Class methods and static methods

This kind of method

  • Class attributes are forClass objectDefined properties
    • Use the assignment statement inclassYou can define class attributes under the keyword
    • Class attributes are used to record characteristics associated with this class
  • Class methodIs aimed atClass objectDefined methods
    • You can access class properties or call other class methods directly from within a class method

Syntax is as follows

@classmethod def CLS: passCopy the code
  • Class methods need to be useddecorator @classmethodTo identify,Tell the interpreter that this is a class method
  • The class methodThe first parameterIt should becls
    • byWhich one classMethod called, within a methodclsisWhich class reference
    • This parameter andInstance methodsThe first argument to isselfsimilar
    • promptOther names are fine, but customarycls
  • throughThe name of the class.callClass method.When calling a method, there is no need to passclsparameter
  • Inside the method
    • Can be achieved bycls. Access the properties of the class
    • Also throughcls. Call other class methods

The sample

  • To define aUtility classEach tool has its ownname
  • demandclassEncapsulates ashow_tool_countClass method that prints the number of objects created using the current class
@classmethod
def show_tool_count(cls):
    """Show total number of tool objects"""
    print("Total tool objects %d" % cls.count)

Copy the code

4.3.2 Static method

  • During development, if required inclassClass encapsulates a method that:
    • There is no need to access instance properties or call instance methods
    • There is no need to access class properties or call class methods
  • At this point, you can wrap the method as a static method

Syntax is as follows

@staticmethod def staticmethod name: passCopy the code
  • A static methodNeed to usedecorator @staticmethodTo identify,Tell the interpreter that this is a static method
  • Call a static method by class name

Example:

  • A static methodshow_helpDisplay game help information
  • Class methodshow_top_scoreDisplays the highest score in history
  • Instance methodsstart_gameStarts the current player’s game
class Game(object):

    # The highest score in the game, class attributes
    top_score = 0

    @staticmethod
    def show_help(a):
        print("Help message: Let zombies Walk into the room.")
        
    @classmethod
    def show_top_score(cls):
        print("The highest score in the game is % D" % cls.top_score)

    def __init__(self, player_name):
        self.player_name = player_name

    def start_game(self):
        print("[%s] Start game..." % self.player_name)
        
        Change the historical high score
        Game.top_score = 999

# 1. Check out game help
Game.show_help()

# 2. Check the game's highest score
Game.show_top_score()

# 3. Create a gameobject and start the game
game = Game("Xiao Ming")

game.start_game()

# 4. Game over, check the highest score of the game
Game.show_top_score()

Copy the code

Approach:

  • Instance methods – Access to instance properties is required internally
    • Instance methods can use class names internally. Accessing class attributes
  • Class methods – Only class attributes need to be accessed inside the method
  • Static methods – Inside methods, there is no need to access instance and class properties

5. The singleton

5.1 Singleton design Pattern

  • Design patterns

    • Design pattern is a summary and refinement of previous work. Generally, the design pattern widely circulated by people is a mature solution to a specific problem
    • Design patterns are used to re-use code, make it easier for others to understand, and ensure code reliability
  • Singleton design pattern

    • Purpose – The class creates an object that has only one instance in the system
    • Each executionThe name of the class ()Object returned,The memory address is the same
  • Application scenarios of the singleton design pattern

    • Music player object
    • Recycle bin object
    • Printer object

5.2 Static Method:__new__

  • useThe name of the class ()When you create an object,PythonThe interpreterFirst of all,Will be called__new__Methods are objectsAllocate space
  • __new__Is aobjectProvided by the base classBuilt-in static methods, has two main functions:
      1. Allocates space for objects in memory
      1. Returns a reference to an object
  • PythonThe interpreter of the objectreferenceAfter, the reference is taken asThe first parameterAnd passed to the__init__methods

The code for overriding the __new__ method is very fixed!

  • rewrite__new__methodsBe sure to return super().__new__(cls)Otherwise, the Python interpreterDon’t getAllocated spaceObject reference.The object’s initialization method is not called
  • Note:__new__Is aA static methodIs required when calledActive transfer clsparameter

class MusicPlayer(object):

    def __new__(cls, *args, **kwargs):
        If no result is returned, the object's initialization method is not called
        return super().__new__(cls)

    def __init__(self):
        print("Initialize the Music Player object")

player = MusicPlayer()

print(player)

Copy the code

5.3 Singleton in Python

  • The singletonclassCreate an object in the systemonly The only instance
    1. To define aClass attribute, and the initial value isNone, for recordingA reference to a singleton object
    2. rewrite__new__methods
    3. ifClass attribute is None, call the parent class method to allocate space and record the result in the class attribute
    4. Returns an object reference to the record in a class property

class MusicPlayer(object):

    Define class attributes to record singleton object references
    instance = None

    def __new__(cls, *args, **kwargs):

        # 1\. Checks whether the class attribute has been assigned
        if cls.instance is None:
            cls.instance = super().__new__(cls)

        # 2\. Returns a singleton reference to a class attribute
        return cls.instance

Copy the code

Only one initialization is performed

  • In each useThe name of the class ()When you create an object,PythonThe interpreter automatically calls two methods:
    • __new__Allocate space
    • __init__Object initialization
  • In the__new__So if I change the method, I get it every timeThe first reference to the object created
  • But: the initialization method is called again

demand

  • Let the initialization action be performed only once

The solution

  1. Define a class attributeinit_flagWhether the tagsInitialization actions have been performed, the initial value isFalse
  2. in__init__In the method, judgeinit_flagIf forFalseThe initialization action is performed
  3. theninit_flagSet toTrue
  4. So, againautomaticcall__init__Method,The initialization action will not be executed again
class MusicPlayer(object):

    Record a reference to the first object created
    instance = None
    Record whether an initialization action has been performed
    init_flag = False

    def __new__(cls, *args, **kwargs):

        # 1\. Check if the class attribute is empty
        if cls.instance is None:
            # 2\. Calls the parent method to allocate space for the first object
            cls.instance = super().__new__(cls)

        # 3\. Returns the object reference saved by the class attribute
        return cls.instance

    def __init__(self):

        if not MusicPlayer.init_flag:
            print("Initialize music Player")

            MusicPlayer.init_flag = True

Create multiple objects
player1 = MusicPlayer()
print(player1)

player2 = MusicPlayer()
print(player2)

Copy the code

Tips

1. Python can automatically concatenate code inside a pair of parentheses:

        return ("House Type: %s\n Total area: %.2f[Remaining: %.2f]\n Furniture: % S"
                % (self.house_type, self.area,
                   self.free_area, self.item_list))
Copy the code

2. Properties of an object can be objects created by another class. The None keyword means nothing, an empty object with no methods or properties, and is a special constant. None can be assigned to any variable.

When comparing None in Python, it is recommended to use the IS judgment

4. The eval() function is very powerful — evaluates a string as a valid expression and returns the result

# Basic math
In [1]: eval("1 + 1")
Out[1] :2

# string repetition
In [2]: eval("' * '* 10")
Out[2] :'* * * * * * * * * *'

# Convert strings to lists
In [3]: type(eval("[1, 2, 3, 4, 5]))
Out[3]: list

# convert strings to dictionaries
In [4]: type(eval("{'name': 'xiaoming', 'age': 18}"))
Out[4]: dict
Copy the code

Never use eval to convert input results directly. For example:

__import__('os').system('ls')

# Equivalent code

import os

os.system("Terminal command")

Copy the code