Explosion liver 60000 words finishing python foundation, quick start python first

1 environmental installation

To learn Python development, you must first learn to install the python environment. I generally use Anaconda + pychar as the development environment. Anaconda is an open source Python Release that contains conda More than 180 science packages and their dependencies, such as, Python, etc. Because it contains a large number of science packages, Anaconda's download file is relatively large (about 531 MB). If you think the installation package is too large, you can use Miniconda.

I have written several articles on environment installation, such as:

Ubuntu20.04 development environment construction: (4 messages) install Anaconda and pychar for Ubuntu 20.04_ AI Hao - CSDN blog

Establishment of Win10 development environment: (4 messages) install Anaconda, pychar, Tensorflow and pytoch on Win10_ AI Hao - CSDN blog

Download the historical version of Anaconda: (4 messages) Anaconda historical version_ AI Hao - CSDN blog , if you do not want to use the latest version, you can find the previous version.

2 Python's first program Hello World

Create a new project, name it "Python foundation", and then click "create"

Then, right-click the project, select "New", and then select "Python File".

Name it "first Python program" and press Enter

Here we have finished creating Python files. Let's try Hello World.

Copy the following code:

   print('hello world')

Then right-click and select Run, or use the shortcut "Ctrl+Shift+F10".

Operation results:

Friends who like to knock commands can choose the command line to run:

python first Python program.py

3 variable definition and type

3.1 what are variables.

For example, I recently bought two books, one for 89 and the other for 118. I want to calculate the total cost of the two books in python:

num1 = 89
num2 = 118
num3 = num1 + num2
print(num3)

Operation result: 207

The so-called variable is the representation of the computer stored value. From the above example, we can draw:

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

In Python, variables have no type. What we call "type" is the type of object in memory that the variable refers to.

The equal sign (=) is used to assign values to variables.

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

3.2 types of variables

How do you know the type of a variable?

In python, as long as a variable is defined and has data, its type has been determined. We developers do not need to actively explain its type, and the system will automatically identify it

You can use type (variable name) to view the type of the variable, for example:

num1 = 89
num2 = 118
num3 = num1 + num2
print(type(num3))

Running result: < class' int '>

3.3 naming rules of variables

Naming rules for variables:

  1. It consists of letters, underscores and numbers, and numbers cannot begin.

  2. python keywords cannot be used.

Keywords are:

      and     as      assert     break     class      continue    def     del
      elif    else    except     exec      finally    for         from    global
      if      in      import     is        lambda     not         or      pass
      print   raise   return     try       while      with        yield
  1. Make a meaningful name and try to know what it means at a glance (improve code readability). For example, the name is defined as name and age is used.

  2. Hump nomenclature

The first small camel case: the first word starts with a lowercase letter; The first letter of the second word is capitalized, for example: myName, aDog

The second is the upper camel case: the first letter of each word is capitalized, such as FirstName and LastName

However, there is another popular naming method among programmers, which is to use the underscore "" To connect all words, such as send_buf

Note: identifiers in python are case sensitive

3.4 common data type conversion

functionexplain
int(x [,base ])Convert x to an integer
long(x [,base ])Converts x to a long integer
float(x )Convert x to a floating point number
complex(real [,imag ])Create a complex number
str(x )Convert object x to string
repr(x )Converts object x to an expression string
eval(str )Used to evaluate a valid Python expression in a string and return an object
tuple(s )Convert sequence s to a tuple
list(s )Convert sequence s to a list
chr(x )Converts an integer to a character
unichr(x )Converts an integer to Unicode characters
ord(x )Converts a character to its integer value
hex(x )Converts an integer to a hexadecimal string
oct(x )Converts an integer to an octal string

give an example

    a = '100' # At this time, the type of a is a string, in which 100 characters are stored
    b = int(a) # At this time, the type of b is integer, and the number 100 is stored in it
    print("a=%d"%b)

4 notes

4.1 single line notes

Start with # and everything on the # right serves as a description, rather than the program to be executed, as an auxiliary description

    # I'm a comment. You can write some function descriptions in it
    print('hello world')

4.2 multiline notes

    '''I am a multi line comment, and can write many, many lines
        Ha ha ha...
        Ha ha ha...
    '''

    '''
    I am a multi line comment, and can write many, many lines
       Ha ha ha...
       Ha ha ha...
    '''
 print('hello world')

4.3 coding

If Chinese is directly used in the program, such as

    print('Hello,I am AI Vast')

If you run the output directly, the program will have coding problems (which is related to the platform)

The solution is: write the following code at the beginning of the program, which is the Chinese comment

    #coding=utf-8

Modified procedure:

    #coding=utf-8
    print('Hello,I am AI Vast')

Operation results:

    Hello

Note: Recommended Methods in python syntax specification:

# -*- coding:utf-8 -*-

5 input and output

5.1 input

input() accepts the input of the expression and assigns the result of the expression to the variable to the left of the equal sign

a = input("Please enter a number:")
print(a)
print(type(a))
b=input("Please enter a string:")
print(b)
print(type(b))
c= input("Please enter a mathematical expression:")
print(c)
print(type(c))
d= input("Please enter a string expression:")
print(d)
print(type(d))

Operation results:

Please enter the number: 123
123
<class 'str'>
Please enter a string: abc
abc
<class 'str'>
Please enter a mathematical expression: 123+456
123+456
<class 'str'>
Please enter a string expression: sdsf,1223
sdsf,1223
<class 'str'>

5.2 output

print() will the input of python

    # Print tips
    print('hello world')

5.2. 1 format output

The following code:

age = 100
print("I this year%d year"%age)
age += 1
print("I this year%d year"%age)
age += 1
print("I this year%d year"%age)

Operation results:

I am 100 years old
 I'm 101 years old
 I am 102 years old

In the program, I see an operator like% which is the formatted output in Python.

    age = 18
    name = "lifeifei"
    print("My name is%s,Age is%d"%(name,age))

Common format symbols

Format symboltransformation
%ccharacter
%sFormat through str() string conversion
%iSigned decimal integer
%dSigned decimal integer
%uUnsigned decimal integer
%oOctal integer
%xHexadecimal integer (lowercase)
%XHexadecimal integer (uppercase letter)
%eIndex symbol (lowercase 'e')
%EIndex symbol (capital "E")
%fFloating point real number
%g%Abbreviations for f and% e
%G%Abbreviations for f and% E

Wrap output

When outputting, if there is \ n, the content after \ n will be displayed on another line

    print("1234567890-------") # Will be displayed on one line
    print("1234567890\n-------") # One line shows 1234567890 and the other line shows-------

Operation results:

1234567890-------
1234567890
-------

6 operator

python supports the following operators

  • Arithmetic operator

Take a = 10 and B = 20 as examples for calculation

operatordescribeexample
+plusAdding two objects a + b outputs the result 30
-reduceGet a negative number or subtract one number from another a - b output - 10
*rideMultiply two numbers or return a string a * b repeated several times, and output the result 200
/exceptx divided by y b / a output 2
//Take and divideReturn the integer part of quotient 9 / / 2 output result 4, 9.0 / / 2.0 output result 4.0
%SurplusReturn the remainder of Division B% a output result 0
**powerReturns the y-power of x, a**b is the 20th power of 10, and the output result is 10000000000000000
>>> 9/2.0
4.5
>>> 9//2.0
4.0
  • Assignment Operators
operatordescribeexample
=Assignment Operators Give the result on the right of the = sign to the variable num=1+2*3 on the left, and the value of num is 7
>>> a, b = 1, 2
>>> a
1
>>> b
2
  • compound assignment operators
operatordescribeexample
+=Additive assignment operatorc += a is equivalent to c = c + a
-=Subtraction assignment operatorc -= a is equivalent to c = c - a
*=Multiplication assignment operatorc *= a is equivalent to c = c * a
/=Division assignment operatorc /= a is equivalent to c = c / a
%=Modulo assignment operatorC% = a is equivalent to C = C% a
**=Power assignment operatorc **= a is equivalent to c = c ** a
//=Integer division assignment operatorc //= a is equivalent to c = c // a
  • Comparison (i.e. relational) operator

The comparison operators in python are shown in the following table

operatordescribeExample
==Checks whether the values of the two operands are equal. If so, the condition becomes true.If a = 3 and B = 3, then (a == b) is true
!=Checks whether the values of the two operands are equal. If the values are not equal, the condition becomes true.If a=1,b=3, (a! = b) is true
<>Checks whether the values of the two operands are equal. If the values are not equal, the condition becomes true.If a = 1 and B = 3, (a < > b) is true. This is similar to= operator
>Check whether the value of the left operand is greater than the value of the right operand. If so, the condition holds.If a=7,b=3, (a > b) is true
<Check whether the value of the left operand is less than the value of the right operand. If so, the condition holds.If a=7,b=3, (a < b) is false
>=Check whether the value of the left operand is greater than or equal to the value of the right operand. If so, the condition holds.If a=3,b=3, (a > = b) is true
<=Check whether the value of the left operand is less than or equal to the value of the right operand. If so, the condition holds.If a=3,b=3, (a < = b) is true
  • Logical operator
operatorLogical expressiondescribeexample
andx and yBoolean and - x and y return False if x is False, otherwise it returns the calculated value of y.(a and b) return to 20.
orx or yBoolean or - returns True if x is True, otherwise it returns the calculated value of y.(a or b) return to 10.
notnot xBoolean not - Returns False if x is True. If x is False, it returns True.not(a and b) returns False

7 judgment statement

7.1 if statement

  • The if statement is used for judgment. Its format is as follows:
    if Conditions to judge:
        What to do when the conditions are established

Example 1:

age = 30
print("------if Judgment start------")
if age >= 18:
    print ("I'm an adult,I can make an appointment with my sister!!!")
print ("------if End of judgment------")

Operation results:

------if Judgment start------
I'm an adult,I can make an appointment with my sister!!!
------if End of judgment------

Example 2:

age = 16
print("------if Judgment start------")
if age >= 18:
    print ("I'm an adult,I can make an appointment with my sister!!!")
print ("------if End of judgment------")

Operation results:

    ------if Judgment start------
    ------if End of judgment------

**Summary: * * the above two examples are just that the values of the age variable are different, but the results are different; It can be seen that the function of if judgment statement is to execute the code only when certain conditions are met, otherwise it will not execute the code

7.2 if else statement

    if condition:
        What to do when conditions are met 1
        What to do when conditions are met 2
        What to do when conditions are met 3
        ......
    else:
        Things to do when conditions are not met 1
        What to do when conditions are not met 2
        What to do when conditions are not met 3
        ......

Example:

age = 30
print("------if Judgment start------")
if age >= 18:
    print ("I'm an adult,I can make an appointment with my sister!!!")
else:
    print("Not yet an adult, can't ask a sister!!!")
print ("------if End of judgment------")

Results 1: age greater than 18

------if Judgment start------
I'm an adult,I can make an appointment with my sister!!!
------if End of judgment------

Result 2: the age was less than 18

------if Judgment start------
Not yet an adult, can't ask a sister!!!
------if End of judgment------

7.3 elif

elif has the following format:

    if xxx1:
        Thing 1
    elif xxx2:
        Thing 2
    elif xxx3:
        Thing 3

explain:

  • When xxx1 is satisfied, do event 1, and the entire if ends
  • When xxx1 is not satisfied, judge xxx2. If xxx2 is satisfied, execute event 2, and then the whole if ends
  • When xxx1 is not satisfied, xxx2 is not satisfied. If xxx3 is satisfied, execute event 3, and then the whole if ends

Example:

score = 66
if 90 <= score <= 100:
    print('This examination, the grade is A')
elif 80 <= score < 90:
    print('This examination, the grade is B')
elif 70 <= score < 80:
    print('This examination, the grade is C')
elif 60 <= score < 70:
    print('This examination, the grade is D')
elif 0 <= score < 60:
    print('This examination, the grade is E')

Can be used with else

   if Male gender:
       Output male characteristics
       ...
   elif Gender is female:
       Output female characteristics
       ...
   else:
       Characteristics of the third sex
       ...

explain:

  • When "gender is male" is satisfied, execute the relevant code of "output male characteristics"

  • When "gender is male" is not satisfied, if "gender is female" is satisfied, execute the relevant code of "output female characteristics"

  • When "gender is male" is not satisfied, and "gender is female" is not satisfied, the code behind else will be executed by default for a long time, that is, the code related to "characteristics of the third gender"

  • elif must be used with if, otherwise an error will occur

7.4 if nesting

if nested format

    if Condition 1:

        Things that meet condition 1 do 1
        Things that meet condition 1 2
        ......

        if Condition 2:
            Things 1 that meet condition 2
            What to do if condition 2 is met
            ......
  • explain
    • If judgment of the outer layer can also be if else
    • The inner if judgment can also be if else
    • Select according to the actual development situation

Application examples of if nesting:

age = 16
girl = False
if age >= 18:
    print("I'm an adult,I can make an appointment with my sister!!!")
    if girl:
        print("Have a girlfriend,Go on a date!!")
    else:
        print("No girlfriend,Make an appointment!!")
else:
    print("Not yet an adult, can't ask a sister!!!")
    if girl:
        print("Not yet an adult,This is puppy love!!")
    else:
        print("Obedient good boy!!!")

Result 1: age= 30;girl= True

I'm an adult,I can make an appointment with my sister!!!
Have a girlfriend,Go on a date!!

Result 2: age= 30;girl= False

I'm an adult,I can make an appointment with my sister!!!
No girlfriend,Make an appointment!!

Result 3: age= 16;girl= False

Not yet an adult, can't ask a sister!!!
Obedient good boy!!!

Result 4: age= 16;girl= True

Not yet an adult, can't ask a sister!!!
Not yet an adult,This is puppy love!!

8 loop, break and continue

8.1 while loop

    while condition:
        Things to do when conditions are met 1
        What to do when the conditions are met 2
        What to do when the conditions are met 3
        ...(ellipsis)...

Example:

i = 0
while i < 5:
    print("The current is the second%d Execution cycle" % (i + 1))
    print("i=%d" % i)
    i += 1

result:

    This is the first execution cycle
    i=0
    This is the second execution cycle
    i=1
    This is the third execution cycle
    i=2
    This is the fourth execution cycle
    i=3
    This is the fifth execution cycle
    i=4

Case 1 Calculate the cumulative sum of 1 ~ 100 (including 1 and 100)

Reference codes are as follows:

# encoding=utf-8
i = 1
sum = 0
while i <= 100:
    sum = sum + i
    i += 1
print("1~100 The cumulative sum of is:%d" % sum)

Operation result: the cumulative sum of 1 ~ 100 is 5050

Case 2 Calculate the cumulative sum of even numbers between 1 and 100 (including 1 and 100)

# encoding=utf-8
i = 1
sum = 0
while i <= 100:
    if i % 2 == 0:
        sum = sum + i
    i += 1

print("1~100 The even cumulative sum of is:%d" % sum)

Operation result: the even cumulative sum of 1 ~ 100 is 2550

8.2 while loop nesting

Similar to if nesting, while nesting means that there is still while in while

The format is as follows

    while Condition 1:

        What to do when condition 1 is met 1
        What to do when condition 1 is met 2   
        ......
        while Condition 2:
            What to do when condition 2 is met 1
            What to do when condition 2 is met
            What to do when condition 2 is satisfied 3
            ...(ellipsis)...

Case 1 requires: print the following graphics:

    *
    * *
    * * *
    * * * *
    * * * * *

Reference code:

    i = 1
    while i<=5:
        j = 1
        while j<=i:
            print("* ",end='')
            j+=1
        print("\n")
        i+=1

Case 2: 99 multiplication table

    i = 1
    while i<=9:
        j=1
        while j<=i:
            print("%d*%d=%-2d "%(j,i,i*j),end='')
            j+=1
        print('\n')
        i+=1

Operation results:

1*1=1  

1*2=2  2*2=4  

1*3=3  2*3=6  3*3=9  

1*4=4  2*4=8  3*4=12 4*4=16 

1*5=5  2*5=10 3*5=15 4*5=20 5*5=25 

1*6=6  2*6=12 3*6=18 4*6=24 5*6=30 6*6=36 

1*7=7  2*7=14 3*7=21 4*7=28 5*7=35 6*7=42 7*7=49 

1*8=8  2*8=16 3*8=24 4*8=32 5*8=40 6*8=48 7*8=56 8*8=64 

1*9=9  2*9=18 3*9=27 4*9=36 5*9=45 6*9=54 7*9=63 8*9=72 9*9=81 

8.3 for loop

Like the while loop, for can complete the function of the loop.

In Python, the for loop can traverse any sequence of items, such as a list or a string.

The format is as follows:

    for Temporary variable in List or string, etc:
        Code executed when the loop satisfies the condition
    else:
        Code executed when the loop does not meet the conditions

Example 1:

name = 'AIHao'
for x in name:
    print(x)

The operation results are as follows:

A
I
H
a
o

Case 2:

name = ''
for x in name:
    print(x)
else:
    print("no data")

The operation results are as follows:

no data

8.5 break

1) for loop

  name = 'AIHao'
  for x in name:
      print('----')
      if x == 'a': 
          break
      print(x)

Operation results:

----
A
----
I
----
H
----

2) while loop

  i = 0
  while i<10:
      i = i+1
      print('----')
      if i==5:
          break
      print(i)

Operation results:

----
1
----
2
----
3
----
4
----

**Summary: * * break is used to end the whole cycle

8.6 continue

1) for loop

  name = 'AIHao'
  for x in name:
      print('----')
      if x == 'a': 
          continue
      print(x)

Operation results:

----
A
----
I
----
H
----
----
o

2) while loop

  i = 0
  while i<10:
      i = i+1
      print('----')
      if i==5:
          continue
      print(i)

Operation results:

----
1
----
2
----
3
----
4
----
----
6
----
7
----
8
----
9
----
10

**Summary: * * continue is used to end this cycle and then execute the next cycle

Note:

  • break/continue can only be used in loops, and cannot be used alone
  • In a nested loop, break/continue only works on the nearest loop

9 string, list, tuple, dictionary

9.1 string

1) The data defined in single quotation marks or double quotation marks is a string, for example:

a='hello'
perhaps
a="hello"

2) The output of the string uses print()

name = 'AI Vast'
position = 'Algorithm Engineer'
address = 'Shijingshan, Beijing'
print('--------------------------------------------------')
print("full name:%s" % name)
print("Position:%s" % position)
print("Company address:%s" % address)
print('--------------------------------------------------')

Operation results:

--------------------------------------------------
full name: AI Vast
 Role: Algorithm Engineer
 Company address: Shijingshan, Beijing
--------------------------------------------------

3) String input

userName = input('enter one user name:')
print("The user name is:%s" % userName)
password = input('Please input a password:')
print("Password is:%s" % password)

Results: (the results are different according to different inputs)

enter one user name:dfsdfsd
 The user name is: dfsdfsd
 Please input a password:qqq
 Password is: qqq

4) Subscript and slice

Use of Subscripts

name = 'abcdef'
print(name[0])
print(name[1])
print(name[2])

Operation results:

a
b
c

section:

Slicing refers to the operation of intercepting part of the operated object. String, list and tuple all support slicing.

Syntax of slice: [start: end: step size]

Note: the selected interval is left closed and right open, that is, it starts from the "start" bit and ends at the previous bit of the "end" bit (excluding the end bit itself).

name = 'abcdef'
print(name[0:3])  # Remove the characters with subscripts 0 ~ 2

Operation results:

abc

9.2 common string operations

If there is a string mystr = 'hello world AIHao and CSDN', the following are common operations

9.2.1 find

Check whether str is included in mystr. If yes, return the starting index value; otherwise, return - 1. Syntax:

mystr.find(str, start=0, end=len(mystr))

Example:

mystr = 'hello world AIHao and CSDN'
print(mystr.find("AIHao", 0, len(mystr)))

Operation results:

12

9.2.2 index

It is the same as the find() method, except that if str is not in mystr, an exception will be reported. Syntax:

mystr.index(str, start=0, end=len(mystr)) 

Example:

mystr = 'hello world AIHao and CSDN'
print(mystr.index("Hao", 0, len(mystr)))

Operation results:

14

9.2.3 count

Returns the number of occurrences of str in mystr between start and end. Syntax:

mystr.count(str, start=0, end=len(mystr))

Example:

mystr = 'hello world AIHao and CSDN'
print(mystr.count("a", 0, len(mystr)))

Operation result: 2

9.2.4 replace

Replace str1 in mystr with str2. If count is specified, the replacement shall not exceed count times. Syntax:

mystr.replace(str1, str2,  mystr.count(str1))

Example:

mystr = 'hello world AIHao and CSDN'
newStr=mystr.replace("a","ee",mystr.count("a"))
print(newStr)

Operation results:

hello world AIHeeo eend CSDN

9.2.5 split

Slice mystr with str as the separator. If maxplit has a specified value, only maxplit substrings will be separated. Syntax:

mystr.split(str=" ", 2)    

Example:

mystr = 'hello world AIHao and CSDN'
newStr=mystr.split(" ",2)
print(newStr)

Operation results:

['hello', 'world', 'AIHao and CSDN']
mystr = 'hello world AIHao and CSDN'
newStr=mystr.split(" ")
print(newStr)

Operation results:

['hello', 'world', 'AIHao', 'and', 'CSDN']

9.2.6 capitalize

Capitalize the first character of the string and lower case the others. Syntax:

mystr.capitalize()

Example:

mystr = 'hello world AIHao and CSDN'
print(mystr.capitalize())

Operation results:

Hello world aihao and csdn

9.2.7 title

Capitalize the first letter of each word in the string and change the others to lowercase, for example:

mystr = 'hello world AIHao and CSDN'
print(mystr.title())

Operation results:

Hello World Aihao And Csdn

9.2.8 startswith

Check whether the string starts with obj. If yes, it returns True. Otherwise, it returns False

mystr.startswith(obj)

Example:

mystr = 'hello world AIHao and CSDN'
ss='hello'
print(mystr.startswith(ss))

Run result: True

9.2.9 endswith

Check whether the string ends with obj. If yes, it returns True; otherwise, it returns False. The usage is the same as above

mystr.endswith(obj)

9.2.10 lower

Convert all uppercase characters in mystr to lowercase

mystr.lower()        

Example:

mystr = 'hello world AIHao and CSDN'
print(mystr.lower())

Operation results:

hello world aihao and csdn

9.2.11 upper

Convert lowercase letters in mystr to uppercase. The usage is the same as above.

mystr.upper()    

9.2.12 ljust

Returns a new string with the original string left justified and filled with spaces to the length width

mystr.ljust(width) 

Example:

mystr = "hello world AIHao and CSDN"
print(mystr.ljust(50))

Operation results:

hello world AIHao and CSDN    

9.2.13 rjust

Returns a new string that is right aligned with the original string and filled with spaces to the length width

mystr.rjust(width)    

Example:

mystr = "hello world AIHao and CSDN"
print(mystr.rjust(30))

Operation results:

    hello world AIHao and CSDN

9.2.14 center

Returns a new string centered on the original string and filled with spaces to the length width. The usage is the same as above.

mystr.center(width)   

9.2.15 lstrip

Delete the white space character to the left of mystr

mystr.lstrip()

9.2.16 rstrip

Remove the whitespace character at the end of the mystr string

mystr.rstrip()    

9.2.17 strip

Delete whitespace characters at both ends of the mystr string

>>> a = "\n\t itcast \t\n"
>>> a.strip()
'itcast'

9.2.18 rfind

It is similar to the find() function, but it starts from the right

mystr.rfind(str, start=0,end=len(mystr) )

9.2.19 rindex

Similar to index(), but starting from the right

mystr.rindex( str, start=0,end=len(mystr))

9.2.20 partition

mystr is divided into three parts by STR, before STR, after STR and after str

mystr.partition(str)

9.2.21 rpartition

Similar to the partition() function, but starting from the right

mystr.rpartition(str)

9.2.22 splitlines

Separated by rows, returns a list containing rows as elements

mystr.splitlines()  

9.2.23 isalpha

Returns True if all characters of mystr are letters, otherwise returns False

mystr.isalpha()  

9.2.24 isdigit

Returns True if mystr contains only numbers, otherwise False

mystr.isdigit() 

9.2.25 isalnum

Returns True if all characters in mystr are letters or numbers, otherwise False

mystr.isalnum()  

9.2.26 isspace

Returns True if mystr contains only spaces, otherwise False

mystr.isspace()   

9.2.27 join

Insert str after each character in mystr to construct a new string

mystr.join(str)

9.3 List

The list is represented by [,...] in the following format:

  namesList = ['xiaoWang','xiaoZhang','xiaoHua']

9.3.1 for loop traversal list

1) Example:

namesList = ['xiaoWang', 'xiaoZhang', 'xiaoHua']
for name in namesList:
    print(name)

result:

    xiaoWang
    xiaoZhang
    xiaoHua

List derivation

1) Common way

a = [x for x in range(4)]
print(a)
b = [x for x in range(3, 4)]
print(b)
c = [x for x in range(3, 19)]
print(c)
d = [x for x in range(3, 19, 2)]
print(d)

Operation results:

[0, 1, 2, 3]
[3]
[3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]
[3, 5, 7, 9, 11, 13, 15, 17]

2) Add if judgment in the process of loop

a = [x for x in range(3, 15) if x % 2 == 0]
print(a)
b = [x for x in range(3, 15) if x % 2 != 0]
print(b)
b = [x for x in range(3, 15)]
print(b)

Operation results:

[4, 6, 8, 10, 12, 14]
[3, 5, 7, 9, 11, 13]
[3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]

3) Multiple for loops

a = [(x, y) for x in range(3, 5) for y in range(3)]
print(a)
b = [(x, y, z) for x in range(3, 5) for y in range(3) for z in range(4, 6)]
print(b)

Operation results:

[(3, 0), (3, 1), (3, 2), (4, 0), (4, 1), (4, 2)]
[(3, 0, 4), (3, 0, 5), (3, 1, 4), (3, 1, 5), (3, 2, 4), (3, 2, 5), (4, 0, 4), (4, 0, 5), (4, 1, 4), (4, 1, 5), (4, 2, 4), (4, 2, 5)]

9.3. 2. While loop through the list

namesList = ['xiaoWang', 'xiaoZhang', 'xiaoHua']
length = len(namesList)
i = 0
while i < length:
    print(namesList[i])
    i += 1

Operation results:

xiaoWang
xiaoZhang
xiaoHua

9.4 common operations of list

The data stored in the list can be modified, such as "add", "delete" and "modify"“

9.4. 1 add elements ("add" append, extend, insert)

Append: you can add elements to the list through append

Example:

    #Define variable A, which has 3 elements by default
    A = ['xiaoWang','xiaoZhang','xiaoHua']
    print("-----List before adding A Data-----")
    for tempName in A:
        print(tempName)
    #Prompt, and add elements
    temp = input('Please enter your name:')
    A.append(temp)
    print("-----After adding, the list A Data-----")
    for tempName in A:
        print(tempName)

result:

-----List before adding A Data-----
xiaoWang
xiaoZhang
xiaoHua
 Please enter your name:xiaohei
-----After adding, the list A Data-----
xiaoWang
xiaoZhang
xiaoHua
xiaohei

Extend: you can add elements from another collection to the list one by one through extend

a = [1, 2]
b = [3, 4]
a.append(b)
print(a)
a.extend(b)
print(a)

result:

[1, 2, [3, 4]]
[1, 2, [3, 4], 3, 4]

Insert: insert(index, object) inserts the element object before the index at the specified position

a = [0, 1, 2]
a.insert(1, 3)
print(a)

result:

[0, 3, 1, 2]

9.4. 2 modify element ("modify")

When modifying an element, it is necessary to determine which element to modify by subscript, and then modify it, for example:

    #Define variable A, which has 3 elements by default
    A = ['xiaoWang','xiaoZhang','xiaoHua']

    print("-----List before modification A Data-----")
    for tempName in A:
        print(tempName)
    #Modify element
    A[1] = 'xiaoLu'
    print("-----After modification, the list A Data-----")
    for tempName in A:
        print(tempName)

result:

    -----List before modification A Data-----
    xiaoWang
    xiaoZhang
    xiaoHua
    -----After modification, the list A Data-----
    xiaoWang
    xiaoLu
    xiaoHua

9.4. 3 find elements ("check" in, not in, index, count)

The so-called search is to see whether the specified element exists

in, not in

Common methods of searching in python are:

  • in (exists). If it exists, the result is true; otherwise, it is false
  • not in (does not exist). If it does not exist, the result is true; otherwise, it is false

demo

    #List to find
    nameList = ['xiaoWang','xiaoZhang','xiaoHua']
    #Gets the name the user is looking for
    findName = input('Please enter the name you want to find:')
    #Find if exists
    if findName in nameList:
        print('The same name was found in the dictionary')
    else:
        print('Can't find')

explain:

As long as the method of in can be used, not in is used in the same way, but not in judges that it does not exist

index, count

index and count are used in the same way as in strings

a = ['a', 'b', 'c', 'a', 'b']
print(a.index('a', 1, 4))
print(a.count('b'))
print(a.count('d'))
print(a.index('a', 1, 3)) # Note the left closed right open section

Operation results:

Traceback (most recent call last):
  File "C:/Users/WH/Desktop/Python Basics/first Python program.py", line 5, in <module>
    print(a.index('a', 1, 3)) # Note the left closed right open section
ValueError: 'a' is not in list
3
2
0

9.4. 4 delete elements ("del, pop, remove")

Analogously, in real life, if a classmate changes classes, the name of the student who left should be deleted; Deleting this function is often used in development.

Common deletion methods of list elements are:

  • del: delete according to subscript
  • pop: delete the last element
  • remove: delete according to the value of the element

demo:(del)

    movieName = ['Pirates of the Caribbean','Hacker empire','First Blood','Lord of the rings','The Hobbit','Fast & Furious']
    print('------Before deletion------')
    for tempName in movieName:
        print(tempName)
    del movieName[2]
    print('------After deletion------')
    for tempName in movieName:
        print(tempName)

result:

    ------Before deletion------
    Pirates of the Caribbean
    Hacker empire
    First Blood
    Lord of the rings
    The Hobbit
    Fast & Furious
    ------After deletion------
    Pirates of the Caribbean
    Hacker empire
    Lord of the rings
    The Hobbit
    Fast & Furious

Example: (pop)

    movieName = ['Pirates of the Caribbean','Hacker empire','First Blood','Lord of the rings','The Hobbit','Fast & Furious']

    print('------Before deletion------')
    for tempName in movieName:
        print(tempName)

    movieName.pop()

    print('------After deletion------')
    for tempName in movieName:
        print(tempName)

result:

    ------Before deletion------
    Pirates of the Caribbean
    Hacker empire
    First Blood
    Lord of the rings
    The Hobbit
    Fast & Furious
    ------After deletion------
    Pirates of the Caribbean
    Hacker empire
    First Blood
    Lord of the rings
    The Hobbit

demo:(remove)

    movieName = ['Pirates of the Caribbean','Hacker empire','First Blood','Lord of the rings','The Hobbit','Fast & Furious']

    print('------Before deletion------')
    for tempName in movieName:
        print(tempName)

    movieName.remove('Lord of the rings')

    print('------After deletion------')
    for tempName in movieName:
        print(tempName)

result:

    ------Before deletion------
    Pirates of the Caribbean
    Hacker empire
    First Blood
    Lord of the rings
    The Hobbit
    Fast & Furious
    ------After deletion------
    Pirates of the Caribbean
    Hacker empire
    First Blood
    The Hobbit
    Fast & Furious

9.4. 5 sort, reverse

sort method rearranges the list in a specific order. The default is from small to large. The parameter reverse=True can be changed to reverse order from large to small.

The reverse method reverses the list.

>>> a = [1, 4, 2, 3]
>>> a
[1, 4, 2, 3]
>>> a.reverse()
>>> a
[3, 2, 4, 1]
>>> a.sort()
>>> a
[1, 2, 3, 4]
>>> a.sort(reverse=True)
>>> a
[4, 3, 2, 1]

9.4. 6 nesting of lists

Similar to the nesting of while loops, lists also support nesting

The elements in a list are a list, so this is the nesting of lists

    schoolNames = [['Peking University','Tsinghua University'],
                    ['Nankai University','Tianjin University','Tianjin Normal University'],
                    ['Shandong University','Ocean University of China']]

Case: there are three offices in a school. Now there are eight teachers waiting for the assignment of stations. Please write a program to complete the random assignment

#encoding=utf-8
import random
# Define a list to hold 3 offices
offices = [[],[],[]]
# Define a list to store the names of 8 teachers
names = ['A','B','C','D','E','F','G','H']
i = 0
for name in names:
    index = random.randint(0,2)    
    offices[index].append(name)
i = 1
for tempNames in offices:
    print('office%d The number of people:%d'%(i,len(tempNames)))
    i+=1
    for name in tempNames:
        print("%s"%name,end='')
    print("\n")
    print("-"*20)

The operation results are as follows:

The number of people in office 1 is:3
BFG

--------------------
The number of people in office 2 is:5
ACDEH

--------------------
The number of people in office 3 is:0


--------------------

9.5 tuples

Python tuples are similar to lists, except that the elements of tuples cannot be modified. The tuple uses parentheses (), and the list uses square brackets [], for example:

aTuple = ('et',77,99.9)
print(aTuple)

Operation results: ('et ', 77, 99.9)

9.5. 1 access tuple

aTuple = ('et',77,99.9)
print(aTuple[0])
print(aTuple[1])

Operation results:

et
77

9.5. 2 modify tuple

aTuple = ('et',77,99.9)
aTuple[0]=111

Operation results:

Traceback (most recent call last):
  File "C:/Users/WH/Desktop/Python Basics/first Python program.py", line 2, in <module>
    aTuple[0]=111
TypeError: 'tuple' object does not support item assignment

From the above running results, it can be concluded that it is not allowed to modify tuple data in python, including deleting elements.

9.5. 3-tuple built-in function count, index

index and count are used in the same way as in strings and lists

>>> a = ('a', 'b', 'c', 'a', 'b')
>>> a.index('a', 1, 3) # Note the left closed right open section
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: tuple.index(x): x not in tuple
>>> a.index('a', 1, 4)
3
>>> a.count('b')
2
>>> a.count('d')
0

9.6 dictionary

A dictionary is a variable container model and can store objects of any type.

Each key = > value pair of the dictionary is separated by colon, and each pair is separated by comma (,). The whole dictionary is included in curly braces {}. The format is as follows:

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

Example:

   info = {'name':'AI Vast', 'id':100, 'sex':'f', 'address':'Beijing China'}

9.6. 1 access the value according to the key

    info = {'name':'AI Vast', 'id':100, 'sex':'f', 'address':'Beijing China'}
    print(info['name'])
    print(info['address'])

result:

    AI Vast
    Beijing China

If you access a key that does not exist, an error will be reported:

info = {'name': 'AI Vast', 'id': 100, 'sex': 'f', 'address': 'Beijing China'}
print(info['age'])

Operation results:

Traceback (most recent call last):
  File "C:/Users/WH/Desktop/Python Basics/first Python program.py", line 2, in <module>
    print(info['age'])
KeyError: 'age'

When we are not sure whether a key exists in the dictionary and want to get its value, we can use the get method and set the default value:

>>> age = info.get('age')
>>> age #The 'age' key does not exist, so age is None
>>> type(age)
<type 'NoneType'>
>>> age = info.get('age', 18) # If the 'age' key does not exist in info, the default value of 18 is returned
>>> age
18

9.7 common operations of dictionary

9.7. 1 modify element

The data in each element of the dictionary can be modified as long as it is found through the key, for example:

info = {'name': 'AI Vast', 'id': 100, 'sex': 'f', 'address': 'Beijing China'}
info['id'] = 150
print('Modified id by:%d' % info['id'])

Result: the modified id is: 150

9.7. 2 add element

When using variable name ['key'] = data, this "key" does not exist in the dictionary, then this element will be added, for example:

info = {'name': 'AI Vast',  'sex': 'f', 'address': 'Beijing China'}
newId = input('Please enter a new ID')
info['id'] = int(newId)

print('After adding id by:%d' % info['id'])

result:

Please enter a new ID123
 After adding id by:123

9.7. 3 delete element

There are several ways to delete a dictionary:

  • del
  • clear()

Example 1:del deletes the specified element

info = {'name': 'AI Vast',  'sex': 'f', 'address': 'Beijing China'}
print('Before deletion,%s' % info['name'])
del info['name']
print('After deletion,%s' % info['name'])

result:

Before deletion,AI Vast
Traceback (most recent call last):
  File "C:/Users/WH/Desktop/Python Basics/first Python program.py", line 4, in <module>
    print('After deletion,%s' % info['name'])
KeyError: 'name'

Example 2:del deletes the entire dictionary

info = {'name': 'AI Vast',  'sex': 'f', 'address': 'Beijing China'}
print('Before deletion,%s' % info)
del info
print('After deletion,%s' % info)

Operation results:

Traceback (most recent call last):
  File "C:/Users/WH/Desktop/Python Basics/first Python program.py", line 4, in <module>
    print('After deletion,%s' % info)
NameError: name 'info' is not defined
 Before deletion,{'name': 'AI Vast', 'sex': 'f', 'address': 'Beijing China'}

Example 3:clear clears the entire dictionary

info = {'name': 'AI Vast',  'sex': 'f', 'address': 'Beijing China'}
print('Before emptying,%s' % info)
info.clear()
print('After emptying,%s' % info)

Operation results:

Before emptying,{'name': 'AI Vast', 'sex': 'f', 'address': 'Beijing China'}
After emptying,{}

9.7. 4 length of dictionary

Use the len() method to find the length of the dictionary, for example:

info = {'name': 'AI Vast',  'sex': 'f', 'address': 'Beijing China'}
print('Length of dictionary:%d' % len(info))

Run result: length of Dictionary: 3

9.7. 5 find all key s in the dictionary

Keys returns a view object containing all keys of the dictionary, for example:

info = {'name': 'AI Vast',  'sex': 'f', 'address': 'Beijing China'}
dicKeys=info.keys()
print(dicKeys)
print(dicKeys[0])

Operation results:

Traceback (most recent call last):
  File "C:/Users/WH/Desktop/Python Basics/first Python program.py", line 4, in <module>
    print(dicKeys[0])
TypeError: 'dict_keys' object is not subscriptable
dict_keys(['name', 'sex', 'address'])

Note: the returned object is a view object, not a list. Many materials say that list is wrong, but it can be converted to a list, for example:

info = {'name': 'AI Vast',  'sex': 'f', 'address': 'Beijing China'}
dicKeys=list(info.keys())
print(dicKeys)
print(dicKeys[0])

Operation results:

['name', 'sex', 'address']
name

9.7. 6 find all value s in the dictionary

The attribute values returns a view list containing all values of the dictionary. The usage is the same as above, for example:

info = {'name': 'AI Vast',  'sex': 'f', 'address': 'Beijing China'}
dicvalues=list(info.values())
print(dicvalues)
print(dicvalues[0])

Operation results:

['AI Vast', 'f', 'Beijing China']
AI Vast

9.7. 7 find the (key, value) of the dictionary

Property items, which returns a list of all (key, value) primitives

info = {'name': 'AI Vast',  'sex': 'f', 'address': 'Beijing China'}
dicItems=info.items()
print(dicItems)

Operation results:

dict_items([('name', 'AI Vast'), ('sex', 'f'), ('address', 'Beijing China')])

9.7. 8 determine whether the key exists

"key in dict" if the key returns true in dictionary dict, otherwise it returns false, for example:

info = {'name': 'AI Vast',  'sex': 'f', 'address': 'Beijing China'}
ss='name' in info
print(ss)

Run result: True

9.7. 9 several ways to traverse the dictionary

1) key to traverse the dictionary

info = {'name': 'AI Vast',  'sex': 'f', 'address': 'Beijing China'}
for key in info.keys():
    print(key)

Operation results:

name
sex
address

2) Traverse the value of the dictionary

info = {'name': 'AI Vast',  'sex': 'f', 'address': 'Beijing China'}
for key in info.values():
    print(key)

Operation results:

AI Vast
f
 Beijing China

3) Traverse dictionary items (elements)

info = {'name': 'AI Vast',  'sex': 'f', 'address': 'Beijing China'}
for item in info.items():
    print(item)

Operation results:

('name', 'AI Vast')
('sex', 'f')
('address', 'Beijing China')

4) Traverse the key value (key value pair) of the dictionary

info = {'name': 'AI Vast', 'sex': 'f', 'address': 'Beijing China'}
for key, value in info.items():
    print("key=%s,value=%s" % (key, value))

Operation results:

key=name,value=AI Vast
key=sex,value=f
key=address,value=Beijing China

10 function

Functions are organized, reusable snippets of code used to implement a single, or associated function.

Function can improve the modularity of application and the reuse rate of code. You already know that Python provides many built-in functions, such as print(). But you can also create your own functions, which are called user-defined functions.

10.1 defining functions

Syntax:

def Function name (parameter list):
    Function body

Example:

# Define a function that can complete the function of printing information
def printInfo():
    print ('------------------------------------')
    print ('         Life is short, I use it Python')
    print ('------------------------------------')

Rules for defining functions:

  • The function code block begins with the def keyword, followed by the function identifier name and parentheses ().
  • Any incoming parameters and arguments must be placed between parentheses, which can be used to define parameters.
  • The first line of the function can optionally use a document string - used to hold the function description.
  • The function content starts with a colon: and is indented.
  • Return [expression] ends the function and selectively returns a value to the caller. A return without an expression is equivalent to returning None.

10.2 calling functions

After the function is defined, it is equivalent to having a code with certain functions. If you want these codes to be executed, you need to call it

Calling a function is very simple. You can complete the call through the function name (), for example:

    # After the function is defined, the function will not be executed automatically. You need to call it
    printInfo()

10.3 comments on functions

Use '' to comment under the function definition, and use the help function to view the comments of the function.

def test(a1, a2):
    '''
    Used to complete the sum of two numbers"
    :param a1:First parameter
    :param a2:Second parameter
    :return:nothing
    '''
    print("%d" % (a1 + a2))


print(help(test))

Operation results:

test(a1, a2)
    Used to complete the sum of two numbers"
    :param a1:First parameter
    :param a2:Second parameter
    :return:nothing

None

10.4 parameters of function

10.4. 1 definition of parameters

Parameter fractal parameter, real parameter

Formal parameters: parameters in parentheses during function definition

Arguments: parameters in parentheses during function call

Formal parameters are equivalent to variables, and arguments are equivalent to the values of variables.

def add2num(a, b):
    c = a + b
    print(c)
    
add2num(11, 22)  # When calling a function with parameters, you need to pass data in parentheses

a. b is a formal parameter; 11 and 12 are arguments

Formal parameters:

Memory units are allocated only when called. At the end of the call, the allocated memory is released immediately.

Valid only inside functions.

Argument:

Can be: constant, variable, expression, function.

When making a function call, the argument must be a definite value.

10.4. 2 classification of parameters

In addition to the required parameters normally defined, Python functions can also use default parameters, variable parameters and keyword parameters, so that the interface defined by the function can not only deal with complex parameters, but also simplify the caller's code.

1) Position parameters

Positional parameters: parameters written from left to right during function definition, such as a and B above

Positional arguments: parameters written from left to right during function call, such as 11 and 12 above

How many position parameters are defined, and how many position arguments must be written when calling. One more or one less cannot be used.

2) Key parameters:

Normally, parameters are passed to functions in order. If you don't want to order, use key parameters.

Parameters that specify parameter names are called key parameters.

When calling a function: func(a=1, b=2). This parameter specifying the parameter name is the key parameter.

When calling a function, the key parameter can be used with the position parameter, but the key parameter must be after the position parameter. Otherwise, an error will be reported.

Example:

def add2num(a, b):
    c = a + b
    print(c)

#Correct calling method
add2num(11, b=22)  # When calling a function with parameters, you need to pass data in parentheses
add2num(a=11, b=22)
add2num(b=11, a=22)
# Wrong calling method.
#add2num(22, a=22)
#add2num(b=11,22)

3) Default parameters

When defining a function, the default parameter must be after the position parameter.

When a function is called, the parameter that specifies the parameter name is called a key parameter.

When you specify a value for a parameter name during function definition, this parameter is called the default parameter.

The key parameters are written in the same way as the default parameters, except that:

The key parameter is to specify the parameter name of the actual parameter or the parameter name of the specified value during function call.

The default parameter is the value that specifies the parameter name when the function is defined.

When defining, if there is a default parameter, this argument may not be written when calling. If the argument is not written, the parameter value of this formal parameter is its default value.

Example:

def add2num(a, b=100):
    c = a + b
    print(c)


add2num(11, b=22)  # When calling a function with parameters, you need to pass data in parentheses
add2num(11)

Operation results:

33
111

4) dynamic parameters: * args **kwargs

*args

* for function definition:

def func(a, b, *args):

pass

*args will receive extra positional arguments passed in during function calls.

*args is a tuple

example:

func(1, 2, 3, 4, 5, 6) function call, because when the function is defined, * args is preceded by formal parameter a, formal parameter b, *args receives the redundant position arguments during the call

A is 1, b is 2, * args is: (3, 4, 5, 6), which is a tuple.

* for function calls:

func(1, 2, *[1, 2, 3, 4]) == func(1, 2, 1, 2, 3, 4)

When there is * in a function call, you should immediately break up the list, tuples, strings and other iterators behind * into positional parameters.

Note that if * is followed by a dictionary, the scattered position parameter is the key of the dictionary

*It can be seen as a for loop.

In the formal parameter, * args can only receive redundant position arguments and become a tuple. Cannot receive critical arguments.

Example:

def calc(*numbers):
    sum = 0
    for n in numbers:
        sum = sum + n * n
    return sum
nums = [1, 2, 3]
# Call mode 1
print(calc(nums[0], nums[1], nums[2]))
#Call mode 2
print(calc(*nums))

Operation results:

14
14

**kwargs:

When defining functions, from the perspective of formal parameters * *:

Receive redundant key arguments and become a dictionary dict.

The key of the dictionary is the variable name of the key argument, and the value of the dictionary is the value of the key argument.

Give the dictionary to the variable name after * *, here is kwargs

From the perspective of arguments * *:

d = {'x':1, 'y':2, 'z':333}

func(**d) # is equivalent to func(x=1,y=2,z=333)

When calling a function, a dictionary can be followed, and then the dictionary will be broken up into the form of key parameters, that is, the form of key=value.

Example:

def person(name, age, **kw):
    print('name:', name, 'age:', age, 'other:', kw)

#Call mode 1
print(person('Michael', 30))
#Call mode 2
print(person('Bob', 35, city='Beijing'))
#Call mode 3
print(person('Adam', 45, gender='M', job='Engineer'))

Operation results:

name: Michael age: 30 other: {}
None
name: Bob age: 35 other: {'city': 'Beijing'}
None
name: Adam age: 45 other: {'gender': 'M', 'job': 'Engineer'}
None

5) When mixing parameters, the parameter order

When defining a function:

From left to right: position parameter > * args > default parameter > * * kwargs

Position parameter > default parameter > * args > * * kwargs can also be used.

Because after the arguments given during the function call meet the location parameters and default parameters, the redundant location arguments will be given to args. This will not report an error.

But * * kwargs must be after * args

The default parameter must be after the position parameter

When calling a function:

From left to right: position arguments > * args > key parameters > * * kwargs

Because * args will be scattered into position arguments during function call, and the key parameters must be behind the position arguments, otherwise an error will be reported. SyntaxError: positional argument follows keyword argument

*args must be after * * kwargs, otherwise syntax error will be reported: syntax error: Iterable argument unpacking follows keyword argument unpacking

summary

Python functions have very flexible parameter forms, which can not only realize simple calls, but also pass in very complex parameters.

The default parameters must be immutable objects. If they are variable objects, there will be logical errors when the program runs!

Note the syntax for defining variable parameters and keyword parameters:

*Args is a variable parameter, and args receives a tuple;

**kw is a keyword parameter, and kw receives a dict.

And how to pass in the syntax of variable parameters and keyword parameters when calling the function:

Variable parameters can be directly passed into: func(1, 2, 3), or you can first assemble a list or tuple, and then pass in: func(*(1, 2, 3)) through * args;

Keyword parameters can be directly passed into: func(a=1, b=2), or you can assemble dict first, and then pass in: func through * * kw (* * {'a': 1, 'B': 2}).

Using * args and * * kw is Python's idiom. Of course, other parameter names can also be used, but it's best to use idioms.

Named keyword parameters are used to limit the parameter names that can be passed in by the caller, and provide default values.

When defining named keyword parameters, do not forget to write the separator * when there are no variable parameters, otherwise the defined parameters will be location parameters.

10.4. 3 transfer of parameters

Python parameter passing must adopt the method of "passing object reference". This method is equivalent to a combination of value passing and reference passing. If the function receives a reference to a variable object (such as a dictionary or list), it can modify the original value of the object - equivalent to passing the object through "pass reference". If the function receives a reference to an immutable object (such as a number, character or tuple), it cannot modify the original object directly - equivalent to passing the object through "pass value".

Example:

attrList = [0, 1, 2, 3, 4, 5]
print("Before change————————————————————————————————")
print(attrList)
def func(i, attrList):
    attrList[i] = attrList[i] * 10


print("After change————————————————————————————————")
for i in range(3):
    func(i, attrList)
print(attrList)

Operation results:

Before change————————————————————————————————
[0, 1, 2, 3, 4, 5]
After change————————————————————————————————
[0, 10, 20, 3, 4, 5]

As you can see, the List has changed. What if immutable elements are passed in?

a = 10
print("Before change————————————————————————————————")
print(a)


def func(c):
    print(id(c))
    c += 2
    print(id(c))
    print("func Functional c Value:", c)

print(id(a))
func(a)
print("After change————————————————————————————————")
print(a)
print(id(a))

Operation results:

Before change————————————————————————————————
10
140724141828160
140724141828160
140724141828224
func Functional c Value: 12
 After change————————————————————————————————
10
140724141828160

The variable a is passed to the func function as a parameter, a reference of a is passed, and the address of a is passed. Therefore, the address of variable c obtained in the function is the same as that of variable A. However, in the function, the value of c changes from 10 to 12. In fact, the memory space occupied by 10 and 12 still exists. After the assignment operation, c points to the memory where 12 is located. A still points to the memory where 10 is located, so print a later, and its value is still 10

10.5 return value of function

To return the result to the caller in the function, you need to use return in the function, for example:

def add2num(a, b):
    c = a + b
    return c


print(add2num(1, 2))

Multiple return values can be returned, for example:

def divid(a, b):
    shang = a // b
    yushu = a % b
    return shang, yushu


sh, yu = divid(5, 2)

10.6 local and global variables

  • A local variable is a variable defined inside a function body

  • Global variables are variables defined outside

    Example:

    a = 1
    def f():
        b = 2
    

    Where a is the global variable and b is the local variable. Local variables are only valid inside the function body, and cannot be accessed outside the function body, while global variables are valid for the following codes.

    Global variables can be used directly in the function body. You can access them directly. However, note that if the assignment operation is performed in the function for data of immutable type, it will not affect the external global variables, because it is equivalent to creating a new local variable, but the name is the same as that of the global. For variable types, If the assignment statement is used, it will also have no impact on the outside, but if the method is used, it will have an impact on the outside.

    g_b = 3
    g_l1 = [1, 2]
    g_l2 = [1, 2, 3]
    
    
    def t1():
        g_b = 2
        g_l1 = []
        g_l2.append(7)
    
    
    t1()
    print(g_b, g_l1, g_l2)
    

    Operation result: 3 [1, 2] [1, 2, 3, 7]

    global keyword
    As mentioned above, if an assignment statement is used, it is equivalent to creating a new variable inside the function and giving a new point, but sometimes we want to make this variable the external global variable. During the assignment operation, we give a new point to the global variable, At this time, the global keyword can be used to indicate that the variable in the function is the global one. The method of use is as follows:

g_b = 3


def t1():
    global g_b
    g_b = 2


t1()
print(g_b)

Operation result: 2

At this time, you will find the global variable g_b also points back, because global g_b indicates that G in the function is specified_ B that's the one outside.

10.7 recursive functions

If a function calls itself internally, the function is a recursive function. Example:

def fact(n):
    if n == 1:
        return 1
    return n * fact(n - 1)


print(fact(5))

Operation result: 120

According to the function definition, the calculation process is as follows:

===> fact(5)
===> 5 * fact(4)
===> 5 * (4 * fact(3))
===> 5 * (4 * (3 * fact(2)))
===> 5 * (4 * (3 * (2 * fact(1))))
===> 5 * (4 * (3 * (2 * 1)))
===> 5 * (4 * (3 * 2))
===> 5 * (4 * 6)
===> 5 * 24
===> 120

The advantages of recursive function are simple definition and clear logic. Theoretically, all recursive functions can be written as loops, but the logic of loops is not as clear as recursion.

Using recursive functions requires attention to prevent stack overflow. In the computer, function calls are realized through the data structure of stack. Whenever a function call is entered, the stack will add one layer of stack frame, and each time the function returns, the stack will reduce one layer of stack frame. Because the size of the stack is not infinite, too many recursive calls will lead to stack overflow. You can try fact(1000).

The way to solve the recursive call stack overflow is through tail recursion optimization. In fact, the effect of tail recursion and loop is the same. Therefore, it is also possible to regard loop as a special tail recursion function.

Tail recursion means that when a function returns, it calls itself, and the return statement cannot contain an expression. In this way, the compiler or interpreter can optimize the tail recursion, so that the recursion itself occupies only one stack frame no matter how many times it is called, and there will be no stack overflow.

The above fact(n) function is not tail recursion because return n * fact(n - 1) introduces a multiplication expression. To change to tail recursion, you need a little more code, mainly to pass the product of each step into the recursive function, for example:

def fact(n):
    return fact_iter(n, 1)

def fact_iter(num, product):
    if num == 1:
        return product
    return fact_iter(num - 1, num * product)

As you can see, return fact_iter(num - 1, num * product) only returns the recursive function itself. Num - 1 and num * product will be calculated before the function call and will not affect the function call.

Fact corresponding to fact(5)_ The call of ITER (5, 1) is as follows:

===> fact_iter(5, 1)
===> fact_iter(4, 5)
===> fact_iter(3, 20)
===> fact_iter(2, 60)
===> fact_iter(1, 120)
===> 120

During tail recursive calls, if optimized, the stack will not grow. Therefore, no matter how many calls, it will not cause stack overflow.

Unfortunately, most programming languages do not optimize tail recursion, nor do Python interpreters. Therefore, even if the above fact(n) function is changed to tail recursion, it will lead to stack overflow.

Summary

The advantage of using recursive functions is that the logic is simple and clear, but the disadvantage is that too deep calls will lead to stack overflow.

Languages optimized for tail recursion can prevent stack overflow through tail recursion. Tail recursion is actually equivalent to loop. Programming languages without loop statements can only realize loop through tail recursion.

The Python standard interpreter does not optimize tail recursion, and any recursive function has the problem of stack overflow.

10.8 anonymous functions

10.8. 1 Definition

You can create small anonymous functions with lambda keywords. This function gets its name from omitting the standard step of declaring a function with def.

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

    lambda [arg1 [,arg2,.....argn]]:expression

Examples are as follows:

sum = lambda a1, a2: a1 * a2

# Call sum function
print("Value of total : ", sum(10, 20))
print("Value of total : ", sum(20, 20))

Output results of the above examples:

Value of total :  200
Value of total :  400

Lambda functions can accept any number of parameters, but can only return the value of one expression

Anonymous functions cannot call print directly because lambda requires an expression

10.8. 2 Application

Example 1: self defined functions are passed as parameters

def fun(a, b, opt):
    print("a =", a)
    print("b =", b)
    print("result =", opt(a, b))


fun(1, 2, lambda x, y: x + y)

Operation results:

a = 1
b = 2
result = 3

Example 2: parameters as built-in functions

Think about it. How does the following data specify sorting by age or name?

stus = [
    {"name":"zhangsan", "age":18}, 
    {"name":"lisi", "age":19}, 
    {"name":"wangwu", "age":17}
]

Sort by name:

stus.sort(key=lambda x: x['name'])
print(stus)

Operation results:

[{'name': 'lisi', 'age': 19}, {'name': 'wangwu', 'age': 17}, {'name': 'zhangsan', 'age': 18}]

Sort by age:

stus.sort(key=lambda x: x['age'])
print(stus)

Operation results:

[{'name': 'wangwu', 'age': 17}, {'name': 'zhangsan', 'age': 18}, {'name': 'lisi', 'age': 19}]

11 file operation

11.1 opening and closing

11.1. 1 open file

In python, using the open function, you can open an existing file or create a new file

Open (file name, access mode)

Examples are as follows:

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

explain:

Access modeexplain
rOpen the file as read-only. The pointer to the file will be placed at the beginning of the file. This is the default mode.
wOpen a file for writing only. If the file already exists, overwrite it. If the file does not exist, create a new file.
aOpen a file for append. If the file already exists, the file pointer will be placed at the end of the file. That is, the new content will be written after the existing content. If the file does not exist, create a new file for writing.
rbOpen a file in binary format for read-only. The file pointer will be placed at the beginning of the file. This is the default mode.
wbOpen a file in binary format for writing only. If the file already exists, overwrite it. If the file does not exist, create a new file.
abOpen a file in binary format for append. If the file already exists, the file pointer will be placed at the end of the file. That is, the new content will be written after the existing content. If the file does not exist, create a new file for writing.
r+Open a file for reading and writing. The file pointer will be placed at the beginning of the file.
w+Open a file for reading and writing. If the file already exists, overwrite it. If the file does not exist, create a new file.
a+Open a file for reading and writing. If the file already exists, the file pointer will be placed at the end of the file. The file is opened in append mode. If the file does not exist, create a new file for reading and writing.
rb+Open a file in binary format for reading and writing. The file pointer will be placed at the beginning of the file.
wb+Open a file in binary format for reading and writing. If the file already exists, overwrite it. If the file does not exist, create a new file.
ab+Open a file in binary format for append. If the file already exists, the file pointer will be placed at the end of the file. If the file does not exist, create a new file for reading and writing.

11.1. 2 close file

close( )

Examples are as follows:

    # Create a new file named test txt
    f = open('test.txt', 'w')

    # Close this file
    f.close()

11.2 reading and writing of documents

11.2. 1 write data (write)

Use write() to write data to a file, for example:

f = open('test.txt', 'w')
f.write('hello hello everyone, I am AI Vast')
f.close()

Operation phenomenon:

be careful:

  • If the file does not exist, create it. If it does exist, empty it first, and then write data

11.2. 2 read data

read(num) can be used to read data from the file. Num represents the length of the data to be read from the file (in bytes). If num is not passed in, it means to read all the data in the file, for example:

f = open('test.txt', 'r')
content = f.read(5)
print(content)
print("-"*30)
content = f.read()
print(content)
f.close()

Operation results:

hello
------------------------------
 hello everyone, I am AI Vast

be careful:

  • If open is to open a file, you don't need to thank the open mode, that is, only write open('test.txt ')
  • If the data is read multiple times, the data to be read later starts from the position after the last reading

11.2. 3. Read lines

Just like when read has no parameters, readlines can read the contents of the whole file at one time in the form of lines, and return a list, in which the data of each line is an element

#coding=utf-8

f = open('test.txt', 'r')
content = f.readlines()
print(type(content))
i=1
for temp in content:
    print("%d:%s"%(i, temp))
    i+=1
f.close()

Operation results:

<class 'list'>
1:hello hello everyone, I am AI Vast

11.2. 4 read data (readline)

#coding=utf-8

f = open('test.txt', 'r')
content = f.readline()
print("1:%s"%content)
content = f.readline()
print("2:%s"%content)

f.close()

Operation results:

1:hello hello everyone, I am AI Vast

2:asfsifhiudh

11.3 common operations of documents

11.3. 1 get the current read / write location

In the process of reading and writing files, if you want to know the current location, you can use tell() to get it, for example:

# Open an existing file
f = open("test.txt", "r")
str = f.read(3)
print("The data read is : ", str)
# Find current location
position = f.tell()
print("Current file location : ", position)
str = f.read(3)
print("The data read is : ", str)
# Find current location
position = f.tell()
print("Current file location : ", position)
f.close()

Operation results:

The data read is :  hel
 Current file location :  3
 The data read is :  lo 
Current file location :  6

11.3. 2 position to a certain position

If you need to operate from another location in the process of reading and writing files, you can use seek()

seek(offset, from) has two parameters

  • Offset: offset
  • from: direction
    • 0: indicates the beginning of the file
    • 1: Indicates the current location
    • 2: Indicates the end of the file

Example 1: set the position as: offset 5 bytes from the beginning of the file

# Open an existing file
f = open("test.txt", "r")
str = f.read(30)
print("The data read is : ", str)

# Find current location
position = f.tell()
print("Current file location : ", position)
# Reset position
f.seek(5, 0)
# Find current location
position = f.tell()
print("Current file location : ", position)
f.close()

Example 2: set the location to 3 bytes from the end of the file

# Open an existing file
f = open("test.txt", "rb")
print("The data read is : ", str)
position = f.tell()
print("Current file location : ", position)

# Reset position
f.seek(-3, 2)

# The data read is: the last 3 bytes of data in the file
str = f.read()
print("The data read is : ", str)

f.close()

Operation results:

The data read is :  <class 'str'>
Current file location :  0
 The data read is :  b'ddf'

11.3. 3 file rename

rename() in os module can rename files

Rename (file name to be modified, new file name)

import os

os.rename("test.txt", "test-1.txt")

11.3. 4 delete file

remove() in os module can delete files

Remove (file name to be deleted)

    import os
    os.remove("test.txt")

11.4 folder related operations

In actual development, it is sometimes necessary to perform certain operations on folders in the form of programs, such as creation, deletion and so on

Just as os module is required for file operation, os module is also required for folder operation

11.4. 1 create folder

    import os

    os.mkdir("aa")

11.4. 2 get the current directory

    import os

    os.getcwd()

11.4. 3 change the default directory

    import os

    os.chdir("../")

11.4. 4 get directory list

    import os

    os.listdir("./")

11.4. 5 delete folder

    import os

    os.rmdir("Zhang San")

11.4. 6. Check whether the folder exists

import os
if not os.path.exists(path):
      os.makedirs(path)

11.4. 7 create multi-level folders

import os
os.makedirs(opDir)

12 object oriented programming

Object Oriented Programming, referred to as OOP, is a programming idea. OOP regards an object as the basic unit of a program. An object contains data and functions that manipulate data.

Process oriented programming regards a computer program as a set of commands, that is, the sequential execution of a set of functions. In order to simplify the program design, the process oriented function is continuously divided into sub functions, that is, the large function is cut into small functions to reduce the complexity of the system.

The object-oriented programming regards the computer program as a set of objects, and each object can receive and process the messages sent by other objects. The execution of the computer program is a series of messages transmitted between various objects.

In Python, all data types can be treated as objects, and of course, you can customize objects. The custom object data type is the concept of Class in object-oriented.

12.1 classes and objects

The most important concepts of object-oriented are Class and Instance. We must keep in mind that Class is an abstract template, such as Student Class, and Instance is a specific "object" created according to Class. Each object has the same method, but its data may be different.

12.1. Class 1

People gather in groups.
A collection of entities with similar internal states and motion laws(Or collectively referred to as abstraction).  
A general term for things with the same attributes and behaviors

A class is abstract. When you use it, you usually find a specific existence of the class and use the specific existence. A class can find multiple objects

12.2. 2 object

The existence of a specific thing ,It can be seen and touched in the real world.
It can be used directly

12.2. 3. Relationship between class and object

Class is the template for creating an instance, while an instance is a specific object. The data owned by each instance is independent of each other;

12.2. 4 definition class

Define a class in the following format:

class Class name:
    Method list

Example: define a Car class

# Define class
class Car:
    # method
    def getCarInfo(self):
        print('Number of wheels:%d, colour%s'%(self.wheelNum, self.color))

    def move(self):
        print("The car is moving...")

explain:

  • There are two types of classes: new class and classic class. Car above is a classic class, and Car(object) is a new class
  • The naming rules of class names follow the "big hump"

12.2. 5 create object

Through the previous section, a Car class is defined; It's like having a drawing for a Car, then the drawing should be handed over to the generation workers to generate

In python, you can create objects according to the defined classes

The format of the created object is:

Object name = Class name()

Create object demo:

# Define class
class Car:
    # move
    def move(self):
        print('The car is running...')

    # whistle
    def toot(self):
        print("The car is whistling...toot toot..")


# Create an object and save its reference with the variable BMW
BMW = Car()
BMW.color = 'black'
BMW.wheelNum = 4 #Number of wheels
BMW.move()
BMW.toot()
print(BMW.color)
print(BMW.wheelNum)

Operation results:

The car is running...
The car is whistling...toot toot..
black
4

12.2.6 __init__ () method

1) Mode of use

def Class name:
    #Initialization function, used to complete some default settings
    def __init__():
        pass

2)__ init__ () method call

# Define car class
class Car:

    def __init__(self):
        self.wheelNum = 4
        self.color = 'blue'

    def move(self):
        print('The car is running, target:Hawaii')

# create object
BMW = Car()

print('The color of the car is:%s'%BMW.color)
print('The number of tires is:%d'%BMW.wheelNum)

Operation results:

The color of the car is:blue
 The number of tires is:4

12.2. 7 magic methods

1) Print id()

If you use print to output BMW, you will see the following information, for example:

# Define car class
class Car:

    def __init__(self):
        self.wheelNum = 4
        self.color = 'blue'

    def move(self):
        print('The car is running, target:Hawaii')

# create object
BMW = Car()

print(BMW)

Operation results:

<__main__.Car object at 0x0000014F596F8400>

That is, you can see the address of the created BMW object in memory

2) Definition__ str__ () method

class Car:
    def __init__(self, newWheelNum, newColor):
        self.wheelNum = newWheelNum
        self.color = newColor
    def __str__(self):
        msg = "well... My color is" + self.color + "I have" + str(self.wheelNum) + "Tires..."
        return msg

    def move(self):
        print('The car is running, target:Hawaii')


BMW = Car(4, "white")
print(BMW)

Operation results:

well... My color is white. I have four tires...

3) Definition__ del__ () method

After the object is created, the python interpreter calls by default__ init__ () method;

When deleting an object, the python interpreter will also call a method by default, which is__ del__ () method

import time


class Animal(object):
    # Initialization method
    # Automatically called after the object is created
    def __init__(self, name):
        print('__init__Method called')
        self.__name = name

    # Deconstruction method
    # When an object is deleted, it is automatically called
    def __del__(self):
        print("__del__Method called")
        print("%s The object was killed immediately..." % self.__name)


# create object
dog = Animal("Pug")
# delete object
del dog
cat = Animal("Persian cat")
cat2 = cat
cat3 = cat
print("---Delete now cat object")
del cat
print("---Delete now cat2 object")
del cat2
print("---Delete now cat3 object")
del cat3
print("The program ends in 2 seconds")
time.sleep(2)

Operation results:

__init__Method called
__del__Method called
 The pug object was killed immediately...
__init__Method called
---Delete now cat object
---Delete now cat2 object
---Delete now cat3 object
__del__Method called
 The Persian cat object was killed immediately...
The program ends in 2 seconds
  • When a variable holds a reference to an object, the reference count of the object will be increased by 1
  • When del is used to delete the object pointed to by the variable, if the reference count of the object is not 1, such as 3, then the reference count will only be reduced by 1, that is, it will become 2. When del is called again, it will become 1. If del is called again, the object will be deleted

summary

  • In python, if the method name is__ xxxx__ (), then it has a special function, so it is called "magic" method
  • When you use print to output an object, as long as you define it yourself__ str__(self) method, the data return ed from this method will be printed

List of common magic methods

Magic methodmeaning
Basic magic methods
_new_(cls[, ...])1. new is the first method called when an object is instantiated 2 Its first parameter is this class, and the other parameters are used to pass directly to init method 3 New determines whether to use the init method, because new can call the constructor of other classes or directly return other instance objects as instances of this class. If new does not return instance objects, init will not be called 4 New is mainly used to inherit an immutable type, such as a tuple or string
_init_(self[, ...])Constructor, the initialization method called when an instance is created
_del_(self)Destructor, a method called when an instance is destroyed
_call_(self[, args...])Allow an instance of a class to be called like a function: x(a, b) calls x.call(a, b)
_len_(self)Defines the behavior when called by len()
_repr_(self)Defines the behavior when called by repr()
_str_(self)Defines the behavior when called by str()
_bytes_(self)Defines the behavior when called by bytes()
_hash_(self)Defines the behavior when called by hash()
_bool_(self)Defines the behavior when called by bool(), which should return True or False
_format_(self, format_spec)Defines the behavior when called by format()
Related properties
_getattr_(self, name)Defines the behavior when a user attempts to get a property that does not exist
_getattribute_(self, name)Defines the behavior when the properties of this class are accessed
_setattr_(self, name, value)Defines the behavior when a property is set
_delattr_(self, name)Defines the behavior when an attribute is deleted
_dir_(self)Defines the behavior when dir() is called
_get_(self, instance, owner)Defines the behavior when the value of the descriptor is obtained
_set_(self, instance, value)Defines the behavior when the value of the descriptor is changed
_delete_(self, instance)Defines the behavior when the value of the descriptor is deleted
Comparison operator
_lt_(self, other)Define the behavior of the less than sign: x < y call x.lt(y)
_le_(self, other)Define the behavior of the less than or equal sign: x < = y call x.le(y)
_eq_(self, other)Define the behavior of the equals sign: x == y calls x.eq(y)
_ne_(self, other)Define the behavior of the inequality sign: X= Y calls x.ne(y)
_gt_(self, other)Define behavior greater than sign: x > y call x.gt(y)
_ge_(self, other)Define the behavior of the greater than or equal sign: x > = y call x.ge(y)
Arithmetic operator
_add_(self, other)Define the behavior of addition:+
_sub_(self, other)Define the behavior of subtraction:-
_mul_(self, other)Define the behavior of multiplication:*
_truediv_(self, other)Define the behavior of true Division:/
_floordiv_(self, other)Define the behavior of integer division://
_mod_(self, other)Define behavior of modulo algorithm:%
_divmod_(self, other)Defines the behavior when called by divmod()
_pow_(self, other[, modulo])Defines the behavior when called by power() or * * operation
_lshift_(self, other)Define the behavior of bitwise left shift:<<
_rshift_(self, other)Define the behavior of bitwise right shift: > >
_and_(self, other)Define bitwise and operational behavior:&
_xor_(self, other)Define the behavior of bitwise XOR operations:^
_or_(self, other)Define the behavior of bitwise or operations:|
Inverse operation
_radd_(self, other)(same as above, called when the left operand does not support the corresponding operation)
_rsub_(self, other)(same as above, called when the left operand does not support the corresponding operation)
_rmul_(self, other)(same as above, called when the left operand does not support the corresponding operation)
_rtruediv_(self, other)(same as above, called when the left operand does not support the corresponding operation)
_rfloordiv_(self, other)(same as above, called when the left operand does not support the corresponding operation)
_rmod_(self, other)(same as above, called when the left operand does not support the corresponding operation)
_rdivmod_(self, other)(same as above, called when the left operand does not support the corresponding operation)
_rpow_(self, other)(same as above, called when the left operand does not support the corresponding operation)
_rlshift_(self, other)(same as above, called when the left operand does not support the corresponding operation)
_rrshift_(self, other)(same as above, called when the left operand does not support the corresponding operation)
_rxor_(self, other)(same as above, called when the left operand does not support the corresponding operation)
_ror_(self, other)(same as above, called when the left operand does not support the corresponding operation)
Incremental assignment operation
_iadd_(self, other)Define the behavior of assignment addition:+=
_isub_(self, other)Define the behavior of assignment subtraction:-=
_imul_(self, other)Define the behavior of assignment multiplication:*=
_itruediv_(self, other)Define the behavior of assignment true Division:/=
_ifloordiv_(self, other)Define the behavior of assigning integer division://=
_imod_(self, other)Define the behavior of assignment modulo algorithm:%=
_ipow_(self, other[, modulo])Define the behavior of the assignment power operation:**=
_ilshift_(self, other)Define the behavior of bitwise left shift of assignment:<<=
_irshift_(self, other)Define the behavior of bitwise right shift of assignment: > >=
_iand_(self, other)Define the behavior of assignment bitwise and operation:&=
_ixor_(self, other)Define the behavior of assignment XOR operation:^=
_ior_(self, other)Defines the behavior of assigning bitwise or operations:|=
unary operator
_neg_(self)Defines the behavior of the plus sign: + x
_pos_(self)Defines the behavior of the minus sign: - x
_abs_(self)Defines the behavior when called by abs()
_invert_(self)Define bitwise negation behavior: ~ x
Type conversion
_complex_(self)Define the behavior when called by complex() (you need to return the appropriate value)
_int_(self)Define the behavior when called by int() (you need to return the appropriate value)
_float_(self)Define the behavior when called by float() (you need to return the appropriate value)
_round_(self[, n])Define the behavior when called by round() (you need to return the appropriate value)
_index_(self)1. When the object is applied in the slice expression, realize the integer cast 2 If you define a custom numeric type that may be used in slicing, you should define index 3 If index is defined, int also needs to be defined and returns the same value
Context management (with statement)
_enter_(self)1. Define the initialization behavior when using the with statement 2 The return value of enter is bound by the target of the with statement or the name after as
_exit_(self, exc_type, exc_value, traceback)1. Define what the context manager should do when a code block is executed or terminated 2 It is generally used to handle exceptions, clear work, or do daily work after the execution of some code blocks
Container type
_len_(self)Defines the behavior when called by len() (returns the number of elements in the container)
_getitem_(self, key)Defines the behavior of obtaining the specified element in the container, which is equivalent to self[key]
_setitem_(self, key, value)Defines the behavior of the specified element in the setting container, which is equivalent to self[key] = value
_delitem_(self, key)Defines the behavior of deleting the specified element in the container, which is equivalent to del self[key]
_iter_(self)Defines the behavior of an element in an iteration container
_reversed_(self)Defines the behavior when called by reversed()
_contains_(self, item)Defines the behavior when the member test operator (in or not in) is used

12.2.8 self

Self can be understood as self, similar to this in C#, for example:

# Define a class
class Animal:

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

    def printName(self):
        print('Name is:%s' % self.name)


# Define a function
def myPrint(animal):
    animal.printName()


dog1 = Animal('Taotao')
myPrint(dog1)
dog2 = Animal('Beibei')
myPrint(dog2)

Operation results:

Name is:Taotao
 Name is:Beibei

summary

The so-called self can be understood as yourself

self can be understood as the this pointer in the class in C + +, which means the object itself

When an object calls its method, the python interpreter will pass the object as the first parameter to self, so developers only need to pass the following parameters

12.2 properties

Attributes are divided into class attributes and instance attributes.

Class attribute belongs to the class, and the class name can be used directly The attribute name is called directly, and there is only one copy of the attribute of the class in memory. Instance properties are__ init__ () properties initialized in the method;
The instance property belongs to the object of the class. You can use the object name Property name, but not class name Property name. Because instance properties are initialized only when an instance is created.

12.2. Class 1 attribute

Class attribute is the attribute owned by the class object. It is shared by the instance objects of all class objects. There is only one copy in memory, which is somewhat similar to the static member variable of the class in C#. Public class attributes can be accessed outside the class through class objects and instance objects, for example:

class People(object):
    name = 'Tom'  #Public class properties
    __age = 12     #Private class properties

p = People()

print(p.name)           #correct
print(People.name)      #correct
print(p.__age)            #Error, private class properties cannot be accessed outside the class through the instance object
print(People.__age)        #Error, private class properties cannot be accessed through class objects outside the class

Access to class properties:

import time


class Test(object):
    name = 'scolia'


a = Test()
print(Test.name)  # Access through classes
print(a.name)  # Access by instance

Operation results:

scolia
scolia

Yes, but if you try to modify this property:

class Test(object):
    name = 'scolia'


a = Test()
Test.name = 'scolia good'  # Modify through class
print(Test.name)
print(a.name)

Operation results:

scolia good
scolia good

We found that both were modified successfully. Try to modify the attribute through the instance again:

class Test(object):
    name = 'scolia'

a = Test()
a.name = 'scolia good'  # Modify by instance
print(Test.name)
print(a.name)

Operation results:

scolia
scolia good

We found that the properties of the class were not modified, while the properties of the instance were modified successfully. Why on earth is this?

In fact, the situation here is very similar to local scope and global scope.

When I access a variable in a function, I will first query whether there is this variable in the function. If not, I will find it in the outer layer. The situation here is that I access a property in the instance, but I don't have it in the instance. I try to create my class to find whether there is this property. If you find it, you have it. If you don't find it, you throw an exception. When I try to modify an immutable property in a class with an instance, I actually don't modify it, but create it in my instance. When I access this property again, I have in my instance, so I don't have to look in the class. If represented by a diagram:

12.2. 2 instance properties (object properties)

Instance properties are_ init_ The attribute defined by the (self) method belongs to the object itself and can only be passed through the object Property cannot be accessed without using a class Property. Example:

class People(object):
    address = 'Shandong' #Class properties
    def __init__(self):
        self.name = 'xiaowang' #Instance properties
        self.age = 20 #Instance properties

p = People()
p.age =12 #Instance properties
print(p.address) #correct
print(p.name)    #correct
print(p.age)     #correct

print(People.address) #correct
print(People.name)    #error
print(People.age)     #error

12.2. 3 private properties

If there is an object, there are two methods to modify its properties

  • Object name Attribute name = Data ----- > Modify directly
  • Object name Method name () --- > indirect modification

In order to save the attribute safely, that is, it cannot be modified at will. The general processing method is

  • Define property as private
  • Add a method that can be called for calling
class People(object):

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

    def getName(self):
        return self.__name

    def setName(self, newName):
        if len(newName) >= 5:
            self.__name = newName
        else:
            print("error:Name length must be greater than or equal to 5")

xiaoming = People("AI Vast")
print(xiaoming.__name)
Traceback (most recent call last):
  File "C:/Users/WH/Desktop/Python Basics/first Python program.py", line 16, in <module>
    print(xiaoming.__name)
AttributeError: 'People' object has no attribute '__name'

Directly calling a private property will report an error. I need to define a method and call the method

class People(object):

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

    def getName(self):
        return self.__name

    def setName(self, newName):
        if len(newName) >= 5:
            self.__name = newName
        else:
            print("error:Name length must be greater than or equal to 5")


xiaoming = People("Zhang San")

xiaoming.setName("wanger")
print(xiaoming.getName())

xiaoming.setName("lisi")
print(xiaoming.getName())

Operation results:

wanger
error:Name length must be greater than or equal to 5
wanger

summary

  • If you need to modify a class attribute outside the class, you must reference it through the class object and then modify it. If the instance object is referenced, an instance attribute with the same name will be generated. In this way, the instance attribute is modified, which will not affect the class attribute. If the attribute with the name is referenced through the instance object, the instance attribute will force the class attribute to be masked, that is, the instance attribute is cited, unless the instance attribute is deleted.
  • In Python, there are no keywords like public and private in C + + to distinguish public attributes from private attributes
  • It is distinguished by attribute naming. If two underscores' _ 'are added in front of the attribute name, It indicates that the attribute is private, otherwise it is public (the same is true for methods. If the method name is preceded by 2 underscores, it means that the method is private, otherwise it is public).

12.3 succession

In the program, inheritance describes the ownership relationship between things. For example, both cats and dogs belong to animals. In the program, it can be described that cats and dogs inherit from animals; Similarly, Persian cats and Balinese cats inherit from cats, while Shapi dogs and spotted dogs inherit enough, as shown below:

# Define a parent class as follows:
class Cat(object):

    def __init__(self, name, color="white"):
        self.name = name
        self.color = color

    def run(self):
        print("%s--Running" % self.name)


# Define a subclass and inherit Cat classes as follows:
class Bosi(Cat):

    def setNewName(self, newName):
        self.name = newName

    def eat(self):
        print("%s--Eating" % self.name)


bs = Bosi("Indian cat")
print('bs Your name is:%s' % bs.name)
print('bs The color of the is:%s' % bs.color)
bs.eat()
bs.setNewName('Persia')
bs.run()

Operation results:

bs Your name is:Indian cat
bs The color of the is:white
 Indian cat--Eating
 Persia--Running

Conclusion:

  • Although subclasses are not defined__ init__ Method, but the parent class has, so this method is inherited when the child class inherits the parent class, so as long as the Bosi object is created, the inherited method is executed by default__ init__ method

  • When a subclass inherits and defines a class, the name of the parent class is in parentheses ()

  • The properties and methods of the parent class will be inherited from the child class

12.3. 1 inheritance of private properties and methods

class Animal(object):

    def __init__(self, name='animal', color='white'):
        self.__name = name
        self.color = color

    def __test(self):
        print(self.__name)
        print(self.color)

    def test(self):
        print(self.__name)
        print(self.color)


class Dog(Animal):
    def dogTest1(self):
        # print(self.__name) #Cannot access private properties of the parent class
        print(self.color)

    def dogTest2(self):
        # self.__test() #Private methods in a parent class cannot be accessed
        self.test()


A = Animal()
# print(A.__name) #The program encountered an exception and cannot access private properties
print(A.color)
# A.__test() #The program encountered an exception and cannot access private methods
A.test()

print("------Split line-----")

D = Dog(name="Little flower dog", color="yellow")
D.dogTest1()
D.dogTest2()

Operation results:

white
 animal
 white
------Split line-----
yellow
 Little flower dog
 yellow

Conclusion:

Private properties cannot be accessed directly through objects, but can be accessed through methods
 Private methods cannot be accessed directly through objects
 Private properties and methods are neither inherited nor accessed by subclasses
 Generally, private attributes and methods are not published, and are often used to do internal things and play a role in security

12.3. 2 multi inheritance

The format of multi inheritance in Python is as follows:

# Define a parent class
class A:
    def printA(self):
        print('----A----')

# Define a parent class
class B:
    def printB(self):
        print('----B----')

# Define A subclass that inherits from A and B
class C(A,B):
    def printC(self):
        print('----C----')

obj_C = C()
obj_C.printA()
obj_C.printB()

Operation results:

----A----
----B----

Conclusion:

python You can inherit more in
 The methods and properties in the parent class will be inherited by the child class

If there is a method with the same name in parent class A and parent class B, which method will be called when calling through a subclass?

# coding=utf-8
class base(object):
    def test(self):
        print('----base test----')


class A(base):
    def test(self):
        print('----A test----')


# Define a parent class
class B(base):
    def test(self):
        print('----B test----')


# Define A subclass that inherits from A and B
class C(A, B):
    pass


obj_C = C()
obj_C.test()

print("Search order:",C.__mro__)  # You can view the order of object search methods of class C

Operation results:

----A test----
Search order: (<class '__main__.C'>, <class '__main__.A'>, <class '__main__.B'>, <class '__main__.base'>, <class 'object'>)

12.3. 3 override parent method

Rewriting means that a subclass has a method with the same name as the parent class, and the method in the subclass will overwrite the method with the same name in the parent class

class Cat(object):
    def sayHello(self):
        print("halou-----1")


class Bosi(Cat):

    def sayHello(self):
        print("halou-----2")


bosi = Bosi()
bosi.sayHello()

Operation results:

halou-----2

12.3. 4. Call the method of the parent class

Calling the parent class__ init__ method

#coding=utf-8
class Cat(object):
    def __init__(self,name):
        self.name = name
        self.color = 'yellow'


class Bosi(Cat):

    def __init__(self,name):
        # Calling the parent class__ init__ Method 1(python2)
        #Cat.__init__(self,name)
        # Calling the parent class__ init__ Method 2
        #super(Bosi,self).__init__(name)
        # Calling the parent class__ init__ Method 3
        super().__init__(name)

    def getName(self):
        return self.name

bosi = Bosi('xiaohua')
print(bosi.name)
print(bosi.color)

Operation results:

xiaohua
yellow

Call the normal method of the parent class

# Parent class
class Dog:
  def bark(self):
    print("Wang Wang barking")
# Subclass inheritance
class XiaoTianQuan(Dog):
  def fly(self):
    print("I can fly")
  # You can override a method with the same name in the parent class
  def bark(self):
    # super(). The method name of the parent class calls the method in the parent class (the first method) (recommended)
    super().bark()
    # Parent class name Method (self) calls the method in the parent class (the second method, python2. X) (not recommended. After the parent class name is modified, it must also be changed here)
    Dog.bark(self)
    # Note: if you call a method with a subclass name, recursive call -- dead loop may occur!
    # XiaoTianQuan.bark(self) # Birth and death cycle
    # It is extended for the specific requirements of subclasses
    print("God like cry...")
xtq = XiaoTianQuan()
xtq.bark()

Operation results:

Wang Wang barking
 Wang Wang barking
 God like cry...

12.4 polymorphism

The concept of polymorphism is applied to strongly typed languages such as Java and C# while Python advocates "duck type".

The so-called polymorphism: when the type at the time of definition is different from the type at the time of runtime, it becomes polymorphism. For example, Python "duck type"

class F1(object):
    def show(self):
        print ('F1.show')

class S1(F1):

    def show(self):
        print ('S1.show')

class S2(F1):

    def show(self):
        print ('S2.show')

def Func(obj):
    print (obj.show())

s1_obj = S1()
Func(s1_obj)
s2_obj = S2()
Func(s2_obj)

Operation results:

S1.show
None
S2.show
None

12.5 static methods and class methods

12.5. Class 1 method

It is a method owned by a class object. It needs to be identified as a class method by the modifier @ classmethod. For a class method, the first parameter must be a class object, Generally, cls is used as the first parameter (of course, variables with other names can be used as the first parameter, but most people are used to using 'cls' as the name of the first parameter, so' cls' is best). It can be accessed through instance objects and class objects.

class People(object):
    country = 'china'

    # Class method, decorated with classmethod
    @classmethod
    def getCountry(cls):
        return cls.country

p = People()
print(p.getCountry())  # You can use instance object references
print(People.getCountry())  # Can be referenced through class objects

Class methods are also used to modify class properties:

class People(object):
    country = 'china'

    # Class method, decorated with classmethod
    @classmethod
    def getCountry(cls):
        return cls.country

    @classmethod
    def setCountry(cls, country):
        cls.country = country


p = People()
print(p.getCountry())  # You can use instance object references
print(People.getCountry())  # Can be referenced through class objects
p.setCountry('japan')
print(p.getCountry())
print(People.getCountry())

Operation results:

china
china
japan
japan

The results show that after modifying the class properties with class methods, the access through class objects and instance objects has changed

12.5. 2 static method

The modifier @ staticmethod needs to be used for modification. Static methods do not need to define more parameters

class People(object):
    country = 'china'

    @staticmethod
    #Static method
    def getCountry():
        return People.country


print People.getCountry()

summary

From the definition forms of class method, instance method and static method, we can see that the first parameter of class method is class object cls, so the attributes and methods of class object must be referenced through cls; If the first parameter of the instance method is the instance object self, the class attribute It may also be an instance attribute (this needs specific analysis). However, if there are class attributes and instance attributes with the same name, the instance attribute has higher priority. There is no need to define additional parameters in the static method. Therefore, if the class attribute is referenced in the static method, it must be referenced through the class object

13 abnormal

When Python detects an error, the interpreter cannot continue to execute. Instead, some error prompts appear, which is the so-called "exception".

13.1 catching exceptions

13.1. 1 catch except ion try... Exception

See the following example:

try:
    print('-----test--1---')
    open('123.txt','r')
    print('-----test--2---')
except IOError:
    pass

Operation results:

-----test--1---

explain:

  • This program can't see any errors because the IOError exception is caught with exception and the handling method is added
  • Pass means that the corresponding implementation is implemented, but nothing is done; If you change pass to print statement, other information will be output

Summary:

  • Put the code that may cause problems in try
  • Put the exception handling code in exception

13.1. 2 Exception Catch multiple exceptions

See the following example:

try:
    print (num)
except IOError:
    print('An error occurred')

The operation results are as follows:

Traceback (most recent call last):
  File "C:/Users/WH/Desktop/Python Basics/first Python program.py", line 2, in <module>
    print(num)
NameError: name 'num' is not defined

Think about it:

The above example program has used except to catch exceptions. Why do you still see error messages?

Answer:

The error type captured by exception is IOError, and the exception generated by the program is NameError, so exception does not take effect

The modified code is:

try:
    print (num)
except NameError:
    print('An error occurred')

The operation results are as follows:

An error occurred

In actual development, the methods of capturing multiple exceptions are as follows:

#coding=utf-8
try:
    print('-----test--1---')
    open('123.txt','r') # If 123 If the txt file does not exist, an IOError exception will be generated
    print('-----test--2---')
    print(num)# If the num variable is not defined, a NameError exception will be generated

except (IOError,NameError):
    #If you want to catch more than one except ion at a time, you can use a tuple
    # The captured error information will be saved in errorMsg
    print(errorMsg)

Operation results:

-----test--1---
Traceback (most recent call last):
  File "C:/Users/WH/Desktop/Python Basics/first Python program.py", line 4, in <module>
    open('123.txt','r') # If 123 If the txt file does not exist, an IOError exception will be generated
FileNotFoundError: [Errno 2] No such file or directory: '123.txt'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:/Users/WH/Desktop/Python Basics/first Python program.py", line 12, in <module>
    print(errorMsg)
NameError: name 'errorMsg' is not defined

be careful:

  • When capturing multiple exceptions, you can put the name of the exception to be captured after exception and store it only in tuple

13.1. 3 get the information description of the exception

13.1. 4 capture all exceptions

13.1.5 else

We should be no stranger to else. In if, its function is to execute when the conditions are not met; The same is true in try... except... That is, if no exception is caught, execute the things in else

try:
    num = 100
    print (num)
except NameError as errorMsg:
    print('An error occurred:%s'%errorMsg)
else:
    print('I'm glad I didn't catch any exceptions')

The operation results are as follows:

100
 I'm glad I didn't catch any exceptions

13.1.6 try...finally...

The try... finally... Statement is used to express such a situation:

In the program, if a piece of code must be executed, that is, whether an exception occurs or not, finally needs to be used at this time. For example, close the file, release the lock, and return the database connection to the connection pool

demo:

import time
try:
    f = open('test.txt')
    try:
        while True:
            content = f.readline()
            if len(content) == 0:
                break
            time.sleep(2)
            print(content)
    except:
        #If an exception occurs during the reading of the file, it will be caught
        #For example, press ctrl+c
        pass
    finally:
        f.close()
        print('Close file')
except:
    print("There is no such file")

explain:

test.txt file, but I intend to use time before printing each line The sleep method pauses for 2 seconds. The reason for this is to make the program run slower. While the program is running, press Ctrl+c to interrupt (cancel) the program.

We can observe that the KeyboardInterrupt exception is triggered and the program exits. But before the program exits, the finally clause is still executed to close the file.

13.2 abnormal transmission

13.2.1. try nested

import time
try:
    f = open('test.txt')
    try:
        while True:
            content = f.readline()
            if len(content) == 0:
                break
            time.sleep(2)
            print(content)
    finally:
        f.close()
        print('Close file')
except:
    print("There is no such file")

Operation results:

There is no such file

13.2. 2 function nested call

def test1():
    print("----test1-1----")
    print(num)
    print("----test1-2----")


def test2():
    print("----test2-1----")
    test1()
    print("----test2-2----")


def test3():
    try:
        print("----test3-1----")
        test1()
        print("----test3-2----")
    except Exception as result:
        print("Exception caught, message is:%s" % result)

    print("----test3-2----")


test3()
print("------Gorgeous dividing line-----")
test2()

Operation results:

----test3-1----
----test1-1----
Exception caught, message is:name 'num' is not defined
----test3-2----
------Gorgeous dividing line-----
----test2-1----
----test1-1----
Traceback (most recent call last):
  File "C:/Users/WH/Desktop/Python Basics/first Python program.py", line 26, in <module>
    test2()
  File "C:/Users/WH/Desktop/Python Basics/first Python program.py", line 9, in test2
    test1()
  File "C:/Users/WH/Desktop/Python Basics/first Python program.py", line 3, in test1
    print(num)
NameError: name 'num' is not defined

Summary:

  • If the try is nested, if the inner try does not catch the exception, the outer try will receive the exception and process it. If the outer try still does not catch the exception, pass it again...
  • If an exception is generated in a function, such as function a - > function B - > function C, and the exception is generated in function C, if the exception is not handled in function C, the exception will be passed to function B. If function B has exception handling, it will be executed according to the processing method of function B; If function B has no exception handling, the exception will continue to be passed, and so on... If all functions are not handled, the default handling of exceptions will be performed at this time, as you usually see
  • Note that in the above figure, when calling test3 function, an exception is generated inside test1 function. This exception is passed to test3 function to complete exception handling. After exception handling, it is not returned to function test1 for execution, but continues to execute in function test3

13.3 throw custom exception

You can raise an exception with the raise statement. Exception / Error objects must have a name and they should be subclasses of the Error or exception class

The following is an example of throwing an exception:

class ShortInputException(Exception):
    '''Custom exception class'''
    def __init__(self, length, atleast):
        #super().__init__()
        self.length = length
        self.atleast = atleast

def main():
    try:
        s = input('Please enter --> ')
        if len(s) < 3:
            # raise raises an exception that you define
            raise ShortInputException(len(s), 3)
    except ShortInputException as result:#The variable x is bound to the wrong instance
        print('ShortInputException: The length entered is %d,The length should be at least %d'% (result.length, result.atleast))
    else:
        print('No exception occurred.')

main()

The operation results are as follows:

Please enter --> 11
ShortInputException: The length entered is 2,The length should be at least 3

be careful

  • In the above procedure, about code #super () Description of init()

    This line of code can be called or not. It is recommended to call because__ init__ Method is often used to initialize the created object. If the parent class is overridden in the child class__ init__ Method means that a lot of initialization work in the parent class is not done, so the stability of the program is not guaranteed. Therefore, in future development, if the parent class is rewritten__ init__ Method, it's best to call the method of the parent class first, and then add your own functions

13.4 exception thrown during exception handling

class Test(object):
    def __init__(self, switch):
        self.switch = switch #switch
    def calc(self, a, b):
        try:
            return a/b
        except Exception as result:
            if self.switch:
                print("The capture is enabled. An exception has been caught. The information is as follows:")
                print(result)
            else:
                #Throw the exception again, and it will not be caught by the exception handler at this time, so as to trigger the default exception handler
                raise


a = Test(True)
a.calc(11,0)

print("----------------------Gorgeous dividing line----------------")

a.switch = False
a.calc(11,0)

Operation results:

The capture is enabled. An exception has been caught. The information is as follows:
division by zero
----------------------Gorgeous dividing line----------------
Traceback (most recent call last):
  File "C:/Users/WH/Desktop/Python Basics/first Python program.py", line 21, in <module>
    a.calc(11,0)
  File "C:/Users/WH/Desktop/Python Basics/first Python program.py", line 6, in calc
    return a/b
ZeroDivisionError: division by zero

14 module

14.1 module introduction

14.1. 1 module in Python

Friends with C programming experience know that if you want to reference sqrt function in C language, you must use the statement #include < math h> Introduce math H this header file, otherwise it cannot be called normally.

So what if you want to reference some other functions in Python?

In Python, there is a concept called module, which is very similar to the header file in C language and the package in Java. For example, to call the sqrt function in Python, you must use the import keyword to introduce the math module. Let's learn about the modules in Python.

To put it mildly: a module is like a toolkit. If you want to use the tools (like functions) in this toolkit, you need to import this module

14.1.2 import

In Python, use the keyword import to import a module. For example, to reference the module math, you can use import math at the beginning of the file.

The shape is as follows:

    import module1,mudule2...

When the interpreter encounters an import statement, if the module is in the current search path, it will be imported.

When calling a function in the math module, you must refer to the following:

  Module name.Function name
  • Think about it:

    Why do I have to add the module name?

  • Answer:

    Because there may be a case where multiple modules contain functions with the same name. At this time, if they are called only through the function name, the interpreter cannot know which function to call. Therefore, when introducing a module like the above, the calling function must add the module name

    import math

    #This will report an error
    print sqrt(2)

    #In this way, the results can be output correctly
    print math.sqrt(2)

Sometimes we only need to use a function in the module. We only need to introduce the function. At this time, we can use the following method:

    from Module name import Function name 1,Function name 2....

Not only functions can be introduced, but also some global variables and classes can be introduced

  • be careful:

    • When importing in this way, you can only give the function name when calling the function, not the module name. However, when two modules contain functions with the same name, the later import will overwrite the previous import. That is, if there is A function() in module A and A function() in module B, if the function in A is introduced first and the function in B is later, the function in module B is executed when the function function is called.
    • If you want to introduce everything in math at once, you can also use from math import *

14.1.3 from...import

Python's from statement allows you to import a specified part from the module into the current namespace

The syntax is as follows:

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

For example, to import the fibonacci function of module fib, use the following statement:

    from fib import fibonacci

be careful

  • Instead of importing the whole FIB module into the current namespace, it will only import fibonacci in fib

14.1.4 from ... import *

It is also feasible to import all the contents of a module into the current namespace. Just use the following Declaration:

    from modname import *

be careful

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

14.1.5 as

    In [1]: import time as tt

    In [2]: time.sleep(1)
    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    <ipython-input-2-07a34f5b1e42> in <module>()
    ----> 1 time.sleep(1)

    NameError: name 'time' is not defined

    In [3]: 

    In [3]: 

    In [3]: tt.sleep(1)

    In [4]: 

    In [4]: 

    In [4]: from time import sleep as sp

    In [5]: sleep(1)
    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    <ipython-input-5-82e5c2913b44> in <module>()
    ----> 1 sleep(1)

    NameError: name 'sleep' is not defined

    In [6]: 

    In [6]: 

    In [6]: sp(1)

    In [7]:

14.1. 6 positioning module

When you import a module, the Python parser searches the module location in the following order:

  1. current directory
  2. If it is not in the current directory, Python searches each directory under the shell variable PYTHONPATH.
  3. If none is found, Python looks at the default path. Under UNIX, the default path is generally / usr/local/lib/python/
  4. The module search path is stored in sys. Of the system module Path variable. The variable contains the current directory, PYTHONPATH and the default directory determined by the installation process.

14.2 fabrication module

14.2. 1 define your own module

In Python, each Python file can be used as a module, and the name of the module is the name of the file.

For example, there is such a file test Py, in test Py defines the function add

test.py

    def add(a,b):
        return a+b

14.2. 2 call the self-defined module

In other files, you can first import test and then pass test Add (a, b). Of course, it can also be introduced through from test import add

main.py

    import test

    result = test.add(11,22)
    print(result)

14.2. 3 test module

In the actual development, when a developer writes a module, in order to make the module achieve the desired effect in the project, the developer will add some test information to the py file, such as:

test.py
    def add(a,b):
        return a+b

    # Used for testing
    ret = add(12,22)
    print('int test.py file,,,,12+22=%d'%ret)

If this file is introduced into other py files at this time, think about whether the code tested will also be executed!

main.py
    import test

    result = test.add(11,22)
    print(result)

Operation phenomenon:

int test.py file,,,,12+22=34
33

At this point, you can find test The test code in py should be executed separately Py file, and should not be referenced in other files

To solve this problem, python has a variable when executing a file__ name__

Run this file directly

def add(a, b):
    return a + b
# # Used for testing
# ret = add(12,22)
# print('int test.py file,,,,12+22=%d'%ret)
print("in test.py file,__name__ is %s "%__name__)

Operation results:

in test.py file,__name__ is __main__ 

import this file in another file

in test.py file,__name__ is test 
33

Summary:

  • Can be based on__ name__ The result of variable can determine whether the python script is directly executed or introduced into execution, so that the test code can be selectively executed

    Execute test py:

def add(a, b):
    return a + b


if __name__ == "__main__":
    # Used for testing
    ret = add(12, 22)
    print('int test.py file,,,,12+22=%d' % ret)
    print("in test.py file,__name__ is %s " % __name__)

Operation results:

D:\ProgramData\Anaconda3\python.exe C:/Users/WH/Desktop/Python Basics/test.py
int test.py file,,,,12+22=34
in test.py file,__name__ is __main__ 

Execute main py :

import test

result = test.add(11, 22)
print(result)

Operation results:

33

14.3 in modules__ all__

14.3. 1 no__ all__

test.py

class Test(object):
    def test(self):
        print("Test Class test function")
def test1():
    print("test1 function")
def test2():
    print("test2 function")

main.py call

from test import *

a=Test()
print(a.test())
print(test1())
print(test2())

Operation results:

Test Class test function
None
test1 function
None
test2 function
None

14.3. 2. There are in the module__ all__

__all__=["Test","test1"]
class Test(object):
    def test(self):
        print("Test Class test function")
def test1():
    print("test1 function")
def test2():
    print("test2 function")

Execute main py

from test import *

a=Test()
print(a.test())
print(test1())
print(test2())

Operation results:

Traceback (most recent call last):
  File "C:/Users/WH/Desktop/Python Basics/first Python program.py", line 6, in <module>
    print(test2())
NameError: name 'test2' is not defined
Test Class test function
None
test1 function
None

summary

If a file has__ all__ Variable, which means that this element that is not in the variable will not be imported when from xxx import *

14.4 packages in Python

14.4. 1. Introduction package

There are two modules with some connections

So put it in the same folder

Use the import file Module import

Import using the from folder import module

Create in msg folder__ init__.py file

In__ init__. Write in py file

Re import using the from folder import module

Summary:

  • Packages organize related modules together, that is, put them in the same folder, and create a folder named__ init__.py file, then this folder is called a package
  • Effectively avoid the problem of module name conflict and make the application organization structure clearer

14.4. 2 __ init__. Role of Py file

__ init__.py controls the import behavior of packages

__ init__.py is empty. It just imports the package, not the modules in the package

__ all__ In__ init__.py file, define a__ all__ Variable, which controls the module imported when the package name is import *

14.5 module release

1. The mymodule directory structure is as follows:

.
├── setup.py
├── suba
│   ├── aa.py
│   ├── bb.py
│   └── __init__.py
└── subb
    ├── cc.py
    ├── dd.py
    └── __init__.py

2. Edit setup Py file

py_modules need to indicate the PY file to be included

from distutils.core import setup

setup(name="AIhao", version="1.0", description="AIhao's module", author="AIhao", py_modules=['suba.aa', 'suba.bb', 'subb.cc', 'subb.dd'])

3. Building modules

python setup.py build

Post build directory structure

.
├── build
│   └── lib.linux-i686-2.7
│       ├── suba
│       │   ├── aa.py
│       │   ├── bb.py
│       │   └── __init__.py
│       └── subb
│           ├── cc.py
│           ├── dd.py
│           └── __init__.py
├── setup.py
├── suba
│   ├── aa.py
│   ├── bb.py
│   └── __init__.py
└── subb
    ├── cc.py
    ├── dd.py
    └── __init__.py

4. Generate and publish compressed package

python setup.py sdist

After packaging, the final release package aihao-1.0 is generated tar. GZ, directory structure

.
├── build
│   └── lib.linux-i686-2.7
│       ├── suba
│       │   ├── aa.py
│       │   ├── bb.py
│       │   └── __init__.py
│       └── subb
│           ├── cc.py
│           ├── dd.py
│           └── __init__.py
├── dist
│   └── AIhao-1.0.tar.gz
├── MANIFEST
├── setup.py
├── suba
│   ├── aa.py
│   ├── bb.py
│   └── __init__.py
└── subb
    ├── cc.py
    ├── dd.py
    └── __init__.py

14.6 module installation and use

14.6. 1 installation method

  1. Find the compressed package for the module
  2. decompression
  3. Enter folder
  4. Execute the command Python setup py install

be careful:

  • If you perform directory installation during install, you can use Python setup Py install -- prefix = install path

14.6. 2 introduction of modules

In the program, use from import to complete the use of the installed module

from Module name import Module name or*

, and then pass test Add (a, b). Of course, it can also be introduced through from test import add

main.py

    import test

    result = test.add(11,22)
    print(result)

14.2. 3 test module

In the actual development, when a developer writes a module, in order to make the module achieve the desired effect in the project, the developer will add some test information to the py file, such as:

test.py
    def add(a,b):
        return a+b

    # Used for testing
    ret = add(12,22)
    print('int test.py file,,,,12+22=%d'%ret)

If this file is introduced into other py files at this time, think about whether the code tested will also be executed!

main.py
    import test

    result = test.add(11,22)
    print(result)

Operation phenomenon:

int test.py file,,,,12+22=34
33

At this point, you can find test The test code in py should be executed separately Py file, and should not be referenced in other files

To solve this problem, python has a variable when executing a file__ name__

Run this file directly

def add(a, b):
    return a + b
# # Used for testing
# ret = add(12,22)
# print('int test.py file,,,,12+22=%d'%ret)
print("in test.py file,__name__ is %s "%__name__)

Operation results:

in test.py file,__name__ is __main__ 

import this file in another file

in test.py file,__name__ is test 
33

Summary:

  • Can be based on__ name__ The result of variable can determine whether the python script is directly executed or introduced into execution, so that the test code can be selectively executed

    Execute test py:

def add(a, b):
    return a + b


if __name__ == "__main__":
    # Used for testing
    ret = add(12, 22)
    print('int test.py file,,,,12+22=%d' % ret)
    print("in test.py file,__name__ is %s " % __name__)

Operation results:

D:\ProgramData\Anaconda3\python.exe C:/Users/WH/Desktop/Python Basics/test.py
int test.py file,,,,12+22=34
in test.py file,__name__ is __main__ 

Execute main py :

import test

result = test.add(11, 22)
print(result)

Operation results:

33

14.3 in modules__ all__

14.3. 1 no__ all__

test.py

class Test(object):
    def test(self):
        print("Test Class test function")
def test1():
    print("test1 function")
def test2():
    print("test2 function")

main.py call

from test import *

a=Test()
print(a.test())
print(test1())
print(test2())

Operation results:

Test Class test function
None
test1 function
None
test2 function
None

14.3. 2. There are in the module__ all__

__all__=["Test","test1"]
class Test(object):
    def test(self):
        print("Test Class test function")
def test1():
    print("test1 function")
def test2():
    print("test2 function")

Execute main py

from test import *

a=Test()
print(a.test())
print(test1())
print(test2())

Operation results:

Traceback (most recent call last):
  File "C:/Users/WH/Desktop/Python Basics/first Python program.py", line 6, in <module>
    print(test2())
NameError: name 'test2' is not defined
Test Class test function
None
test1 function
None

summary

If a file has__ all__ Variable, which means that this element that is not in the variable will not be imported when from xxx import *

14.4 packages in Python

14.4. 1. Introduction package

There are two modules with some connections

[external chain picture transferring... (img-SLQzBFTR-1630474706485)]

So put it in the same folder

[external chain picture transferring... (IMG pcvsaxtz-1630474706486)]

Use the import file Module import

[external chain picture transferring... (img-w8G4goMf-1630474706486)]

Import using the from folder import module

[external chain picture transferring... (img-sruI0KU8-1630474706487)]

Create in msg folder__ init__.py file

[external chain picture transferring... (img-303ePJ8i-1630474706487)]

In__ init__. Write in py file

[external chain picture transferring... (img-a9ithVil-1630474706488)]

Re import using the from folder import module

[external chain picture transferring... (img-6ClhSwqC-1630474706488)]

Summary:

  • Packages organize related modules together, that is, put them in the same folder, and create a folder named__ init__.py file, then this folder is called a package
  • Effectively avoid the problem of module name conflict and make the application organization structure clearer

14.4. 2 __ init__. Role of Py file

__ init__.py controls the import behavior of packages

__ init__.py is empty. It just imports the package, not the modules in the package

__ all__ In__ init__.py file, define a__ all__ Variable, which controls the module imported when the package name is import *

14.5 module release

1. The mymodule directory structure is as follows:

.
├── setup.py
├── suba
│   ├── aa.py
│   ├── bb.py
│   └── __init__.py
└── subb
    ├── cc.py
    ├── dd.py
    └── __init__.py

2. Edit setup Py file

py_modules need to indicate the PY file to be included

from distutils.core import setup

setup(name="AIhao", version="1.0", description="AIhao's module", author="AIhao", py_modules=['suba.aa', 'suba.bb', 'subb.cc', 'subb.dd'])

3. Building modules

python setup.py build

Post build directory structure

.
├── build
│   └── lib.linux-i686-2.7
│       ├── suba
│       │   ├── aa.py
│       │   ├── bb.py
│       │   └── __init__.py
│       └── subb
│           ├── cc.py
│           ├── dd.py
│           └── __init__.py
├── setup.py
├── suba
│   ├── aa.py
│   ├── bb.py
│   └── __init__.py
└── subb
    ├── cc.py
    ├── dd.py
    └── __init__.py

4. Generate and publish compressed package

python setup.py sdist

After packaging, the final release package aihao-1.0 is generated tar. GZ, directory structure

.
├── build
│   └── lib.linux-i686-2.7
│       ├── suba
│       │   ├── aa.py
│       │   ├── bb.py
│       │   └── __init__.py
│       └── subb
│           ├── cc.py
│           ├── dd.py
│           └── __init__.py
├── dist
│   └── AIhao-1.0.tar.gz
├── MANIFEST
├── setup.py
├── suba
│   ├── aa.py
│   ├── bb.py
│   └── __init__.py
└── subb
    ├── cc.py
    ├── dd.py
    └── __init__.py

14.6 module installation and use

14.6. 1 installation method

  1. Find the compressed package for the module
  2. decompression
  3. Enter folder
  4. Execute the command Python setup py install

be careful:

  • If you perform directory installation during install, you can use Python setup Py install -- prefix = install path

14.6. 2 introduction of modules

In the program, use from import to complete the use of the installed module

from Module name import Module name or*

Keywords: Python Pycharm Deep Learning

Added by alivec on Fri, 17 Dec 2021 16:08:11 +0200