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

Getting started with Python Basics

編輯:Python

Python

    • One 、 notes
    • Two 、 Variable
    • 3、 ... and 、 data type
      • The plural
        • Define a complex number
        • Obtain the imaginary and real parts of a complex number
    • Four 、 Input and output
    • 5、 ... and 、 operation
    • 6、 ... and 、 Conditional statements
    • 7、 ... and 、 loop
    • 8、 ... and 、 character string
    • Nine 、 section
      • grammar
    • 11、 ... and 、 character string str
      • Common operation methods
        • lookup
        • modify
        • Judge
    • Twelve 、 list list
      • Format
      • Common operations
        • lookup
          • Subscript
          • function
        • Judge
        • increase
        • Delete
        • modify
        • Copy
        • Loop traversal of list
        • List nesting
    • 13、 ... and 、 Tuples tuple
      • Format
      • Common operations of tuples
    • fourteen 、 Dictionaries dict
      • Create a dictionary
      • Dictionary common operation
        • increase
        • Delete
        • Change
        • check
        • Traverse
    • 15、 ... and 、 aggregate set
      • Create set
      • Common operation methods of collection
        • increase
        • Delete
        • lookup
    • sixteen 、 Common operator
    • seventeen 、 Public methods
    • eighteen 、 Container type conversion
    • nineteen 、 The derived type
      • List derivation
        • belt if List derivation of
        • Multiple for Loop to implement the list derivation
      • Dictionary derivation
      • Set derivation
    • twenty 、 function
      • Function documentation
      • The return value of the function
      • Parameters
        • Positional arguments
        • Key parameters
        • Default parameters
        • Indefinite length parameter
        • unpacking
        • Exchange variable values
    • The 21st 、 quote
      • Reference as argument
    • Twenty-two 、 Variable and variable types
    • 23 、 recursive
    • Twenty-four 、lambda expression
      • grammar
      • Experience cases
      • lambda application
        • With judgment lambda
        • List data according to dictionary key Sort
    • twenty-five 、 Built in higher order function
      • abs- It's not a higher-order function
      • round- It's not a higher-order function
      • map function
      • reduce function
      • filter function
      • zip function
      • eval function
    • hexacosa- 、 File operations
      • The basic operation of the file
      • open
      • Quick experience
      • Access pattern
      • read
      • Move the pointer position
    • twenty-seven 、 object-oriented
    • Twenty-eight 、 Classes and objects
      • Define a class and object
      • self
      • Add or get attributes
        • Add and get object properties outside the class
        • Get the object properties in the class -self
      • Magic methods
        • —init—()
        • Parameterized —init—(self)
        • —str—(self)
        • —del—(self)
      • Inherit
        • Single inheritance
        • Multiple inheritance
        • rewrite
        • Multiple inheritance
        • View inheritance relationships
        • super()
      • Private property
        • Get and modify private properties
      • encapsulation
      • polymorphic
      • Class properties and instance properties
        • Class properties
        • Modify class properties
      • Class methods and static methods
        • Class method
        • Static methods
    • Twenty-nine 、 abnormal
      • Catch the specified exception
      • Catch all exceptions
      • else
      • finally
      • Custom exception
    • thirty 、 modular
      • Guide module mode
      • Sequence of module positioning
      • —all—
    • Thirty-one 、 package
      • Create a package
      • Import package
    • Thirty-two 、 Other intellectual
      • —dict—
    • python The date and time of
      • time tuples
      • Get the current time
      • Get the formatted time
      • Format date
      • Get the calendar of a month
      • Time modular
      • The calendar (Calendar) modular
    • Other related modules and functions

Document address :https://www.python.org/doc/
Chinese document address :https://docs.python.org/zh-cn/3.8/py-modindex.html

python Parser

IDE: Abbreviation of integration tool

effect : Run the file

  • ipython: Is an interactive parser , You can save variables automatically 、 Automatic indentation
  • cpython:c Official parser for language development , Widely applied
  • Other parsers

One 、 notes

Two ways

# Single-line comments 
""" Multiline comment ( Three double quotes ) """
''' Multiline comment ( Three single quotes )'''
# Shortcut key :ctrl+/

Two 、 Variable

In the program , Data is temporarily stored in memory , The variable is just the name of the memory address of the current data when storing data .

 Variable name = value # It is not said here that the type of variable must be specified 

The variable name should conform to the identifier naming rules :

  • By digital 、 Letter 、 Underline composition
  • Can 't start with a number
  • You can't use built-in keywords
  • Case sensitive

Naming habits :

  • See the name and know the meaning
  • Hump
  • Little hump
  • Underline

3、 ... and 、 data type

character string :String

Metagroup type : Array

List :list class

Dictionary type :map class

aggregate :set

Boolean type : representative False, The numbers represent 0 Of , All kinds of brackets are empty , There are only two values here , One is True, One is False

Test data type :type( data )

The plural

Define a complex number

  1. Just assign a value to the variable directly
  2. Use complex
a=3+2j
print(a)
b=complex(3,4)
print(b)
(3+2j)
(3+4j)

Obtain the imaginary and real parts of a complex number

a=3+2j
print(a)
print(a.real)
print(a.imag)
(3+2j)
3.0
2.0

Four 、 Input and output

Here is the normal output , There are three ways to output

x =input(' Please enter an integer ')
print(x)
name='aabbcc'
age=20
str=' My name is {}, I this year {} year '
print(str.format(name,age))
name='aabbcc'
age=20
print(f' My name is {
name}, This year, {
age} year ')

Here we use a format function , Very flexible

s=" In today's {} attend class;class begins , On is {} course "
print(s.format("6 building ","python"))
 In today's 6 Dong has classes , On is python course

Comparison operator == It means that the characters are the same and the corresponding addresses should also be the same ,equal It means that the characters are the same .

  • It uses $ Template to realize variable input
from string import Template
string =Template(" I wish you ${x} happy ")
string.substitute(x=' Birthday ')
# The advantage of this is that it can be changed at any time x Data type and data 
  • Input and output according to the format
import datetime
name = str(input(" Please enter your name :"))
birthday =int(input(" Please enter your year of birth :"))
age = datetime.date.today().year -birthday
print("%s Hello! ! This year you %d year ."%(name,age))

Here is the formatted output

%s: character string

%d: Decimal integer

%f: Floating point numbers

%c: character

\n: Line break

\t: tabs

Input

x =input(' Please enter an integer ')
print(x)

Common functions for converting data types

int()
float()
str()
list()
tuple() # Tuples
eval() # Convert to the original type

5、 ... and 、 operation

  1. division :/ Indicates division with decimals
  2. //: To divide or divide
  3. The next power :2 Of 8 Power means :2**8
  4. The assignment operation , You can assign multiple values ,a=b=c=1; a,b,c,d=1,2,3,“aadd” ; Direct data exchange :x,y=y,x Can be realized
  5. Logical operations :and 、or、not, To express with 、 or 、 Not
  6. innot in It means that in this sequence, it will return true, If not, go back false
for i in (1,23)
#for(int i=1;i<23;i++)
  1. Shift operation : Move left to get bigger , How many times you move is equivalent to how many times you multiply 2; Move right smaller , It's equivalent to dividing by how many 2; Vacancies are filled 0
  2. Bitwise AND 、 Press bit or 、 Exclusive or ^、 Take the opposite ( According to the not +1)
  3. Dynamic change : The data doesn't change , Each number has a corresponding address , Only the identification corresponding to the number will change
  4. () Indicates range or priority
# Talk about an operational logic 
d=10
d*=1+2
print(d)
# The result is 30, First calculate the right side of the assignment , Count the left 

6、 ... and 、 Conditional statements

if……elif ……else

Execute the process : When a certain code meets the conditions, it can be executed , Other subsequent code will not execute

age=50
if age < 18:
print(f' Your age is {
age}, You are a child laborer ')
elif (age>=18)and (age<=60):
print(f' Your age is {
age}, You are a legal working people ')
else:
print(f' Your age is {
age}, You are a retired worker ')

Simplified writing

elif 18<=age<=60

age=50
if age < 18:
print(f' Your age is {
age}, You are a child laborer ')
elif 18<=age<=60:
print(f' Your age is {
age}, You are a legal working people ')
else:
print(f' Your age is {
age}, You are a retired worker ')

random number

random class

import random
x=random.randint(1,20)
print(x)

Ternary operator

c=a if a>b else b

a=1
b=2
c=a if a>b else b
print(c)

7、 ... and 、 loop

while grammar

i=0;
while True:
if i==9:
break;
print(i)
i+=1 # Here's what's interesting ,i++ It doesn't exist 
  • break: End cycle

  • continu: Terminate the current execution , Other execution of the loop is not affected

for loop

for a in [1,10]:
print(a)
1
10
for i in range(1,10):# Here's what's interesting , To use range() function 
print(i)

while…else

Execute the code after the loop ends normally , Code cannot be executed after abnormal execution

This is because of cycles and else The following content has certain dependencies

# Cases that normally end 
i=0
while i<=5:
print(i)
i+=1
else:
print('end')
1
2
3
4
5
end
# break Cases that end in advance 
i=1
while i<=5:
if i==3:
print(' An error occurred ')
break
print(i)
i+=1
else:
print('end')
1
2
An error occurred
# continue Cases that end in advance 
i=0
while i<=5:
i+=1
if i==5:
print(' An error occurred ')
break
print(i)
else:
print('end')
1
2
3
4
An error occurred

for…else

and while equally , It also needs to be executed at the normal end of the program , If the program does not end normally ,else Later things will not be implemented .

for a in (1,10):
print(a)
else:
print(' The loop ends , Print response ')

8、 ... and 、 character string

  • Single quotation marks 、 Double quotes 、 Three quotation marks can lead to string
name1='cch1'
name2="cch2"
name3='''cch3'''
  • Input and output
name=input(' Type in your name :')
print(' My name is '+name)
print(' My name is %s'%name)
print(f' My name is {name}')
  • [ Subscript ]

    name[0]
    

Nine 、 section

  • Slicing refers to the operation of intercepting part of the operation object , character string 、 list 、 Tuples all support slicing .

grammar

 Sequence [ The following table of starting positions : The following table of ending positions : step ]

Pay attention to is :

  • The following table does not contain the data corresponding to the end position , Both positive and negative numbers are OK
  • The step size is to select the gap , The default is 1( If you don't write it, it's just 1), You can also customize it , Both positive and negative numbers are OK
  • If it's a negative number , Indicates the reverse value
  • -1 The small mark of is the last by default
str1='0123456'
print(str1[2:5:2])
# The result is 24
# If you don't write the beginning , The default from the 0 Start 
str1='0123456'
print(str1[:5:1])
# The result is 01234
# If you don't write the end , Default to the last , And it contains the last 
str1='0123456'
print(str1[3:])
# The result is 3456
# If the step size is negative , It means counting in reverse order 
str1='0123456'
print(str1[::-1])
# The result is 6543210
# The first two are negative numbers 
str1='0123456'
print(str1[-4:-1])
# The result is 345, Because it does not contain -1 The number in position , That is, it does not contain the last number 
# All three numbers are negative 
str1='0123456'
print(str1[-4:-1:-1])
# Cannot select data , Because the two directions are mutually exclusive , from -4 To -1 It is selected from left to right , however -1 Step size means to select from right to left 
# All three numbers are negative 
str1='0123456'
print(str1[-1:-4:-1])
# 543, Because the selected direction is consistent 

11、 ... and 、 character string str

Common operation methods

lookup

Find the position of the substring in the string or the number of occurrences

  • find(): Check whether a string is contained in the string , If it exists, return to the following table at the beginning of this string , Otherwise return to -1

  • Be careful : The start position and end position can be omitted , Means to find... In the whole string sequence

  • The following is grammar :

 String sequence .find( String , Starting position subscript , Subscript of end position )
# The subscripts of the starting and ending positions can be omitted here ,
string='asdffgghfj'
print(string.find('sdf',2))
# return -1, Because from 2 The string at the beginning of position does not contain the string we require ‘sdf’
  • index(): Check whether a string is included in this string , If it exists, it returns the subscript at the beginning of the string , Otherwise, the report will be wrong
  • Here is the grammar
 String sequence .index( String , Starting position subscript , Subscript of end position )
# The subscripts of the starting and ending positions can be omitted here ,
string='asdffgghfj'
print(string.index('sdf',2))

  • count(): Indicates the number of times this substring appears in the string
  • If it doesn't exist , Times is 0
 String sequence .count( String , Starting position subscript , Subscript of end position )
# The subscripts of the starting and ending positions can be omitted here ,
string='asdffgghfj'
print(string.count('sdf',2))
# The result here is 0

The following functions are similar to the corresponding functions above , But the search direction is from On the right side Start looking for , The following table starts from left to right

  • rfind():
  • rindex():

modify

  • replace(): Replace , This substitution does not change the value of the string itself , Its own function will have a return value , Indicates the modified result , If you need this return value , You need a new variable to assign
  • In other words, here , Strings are immutable types , Because of our operation on strings , Has not changed to its own value
  • The grammar is as follows :
 String sequence .replace( Old characters , New character , Number of replacements )
# The number of replacements can be omitted , Not writing means to replace all ; If the number of replacements > Number of string occurrences , Means replace all , But there is no error 
string='asdffgghfj'
print(string.replace('f',' False '))
# result :asd False False ggh False j
  • split(): Return a list , This method will lose the segmentation symbol
  • grammar :
string.split( Split character ,num)
# num Indicates the number of times the split character appears , That is, the number of returned data is num+1 individual 
string='asd False False ggh False j'
print(string.split('False'))
# Output results :['asd ', ' ', ' ggh ', ' j'], Here you can see , It's all divided , and False Itself has been removed 
string='asd False False ggh False j'
print(string.split('False',2))
# The result here is :['asd ', ' ', ' ggh False j'], Here you can see , This will return to 2+1 Data , That is, only the front 2 Data 
  • join(): Merge the strings in the list into a large string
  • The grammar is as follows :
 Characters or substrings .join( A sequence of multiple strings )
# Characters or substrings Indicate what method you want to use to connect the contents of this sequence 
list=['aa','bb','cc']
string='...'.join(list)
print(string)
# The result is :aa...bb...cc
  • capitalize(): Convert the first character to uppercase , Of course, uppercase characters in other places will also be converted to lowercase .
  • The grammar is as follows :
 character string .capitalize()
string='asd False False ggh False j'
print(string.capitalize())
# Asd false false ggh false j
  • title(): Convert the initials of all characters into uppercase letters , Capital letters elsewhere will become lowercase .
  • The grammar is as follows :
 character string .title()
string='asd False False ggh False j'
print(string.title())
# Asd False False Ggh False J
  • lower(): Capitalize to lowercase
  • upper(): Small to capital

Here is another time : String functions do not modify the string itself , Instead, there will be a return value , The modified result is in the return value .

  • Delete the white space character of the string

  • lstrip(): Delete the white space character on the left

  • rstrip(): Delete the white space character on the right

  • strip(): Delete the blank characters on the left and right

string=' asd False False ggh False j '
print(string.rstrip())
# asd False False ggh False j
  • string alignment
  • ljust(): Returns an original string left aligned , And use the specified characters ( Default space ) Fill in new characters of corresponding length
  • grammar :
string.ljust( length , Fill character )
string="aabbcc"
print(string.ljust(10,'*'))
# aabbcc****
  • rjust(): Align right
  • center(): Align in the middle
string="aabbcc"
print(string.rjust(10,'*'))
# ****aabbcc
string="aabbcc"
print(string.center(10,'*'))
# **aabbcc**
string="aabbcc"
print(string.center(9,'*'))
# **aabbcc*

If the middle is aligned , When the padding character is odd , There is no absolute alignment

Judge

The result returned by the judgment function is False Or is it True

  • Judge the beginning and the end

  • startswith(): Check whether the string starts with the specified string within the specified range , Is to return True, Otherwise return to False

  • grammar :

string.startswith( Substring , Starting position subscript , End position subscript )
# The last two parameters can be omitted 
  • endswith(): Check whether the string ends with the specified string within the specified range , Is to return True, Otherwise return to False
  • grammar :
string.endswith( Substring , Starting position subscript , End position subscript )
# The last two parameters can be omitted 
string='asd False False ggh False'
print(string.endswith('false'))
# False

Here's what's interesting , Here is strictly case sensitive

  • Determine whether the string is all letters or numbers
  • isalpha(): If it is all at least one character and all characters are all characters , All letters return true , Otherwise return false
  • isdigit(): If it's all numbers, it returns true .
string1='hello'
string2='hello123'
string3='Hello'
string4='123'
print(string1.isalpha())
print(string2.isalpha())
print(string3.isalpha())
print(string4.isdigit())
# True
# False
# True
# True

This is regardless of case

  • isalnum(): All letters or numbers are true
  • isspace(): All blank is true
string1=' '
string2='hello123'
print(string1.isspace())# True
print(string2.isalnum())# True

Twelve 、 list list

Store multiple data , And the data that can be modified is the list .

Format

[ data 1, data 2, data 3……]

Lists can store a lot of data , You can also store data of different data types , But in real business , We usually store the same data type in the same list

Common operations

lookup

Subscript
name=['aaa','bbb','ccc']
print(name[0])
# aaa
function
  • index(): Returns the subscript of the specified data location , But if it doesn't appear, it will report an error
  • grammar :
list.index()
name=['aaa','bbb','ccc']
print(name.index('bb'))

  • count(): Specify the number of times the data appears in the current list
  • grammar :
list.count()
  • len(): The length of the sample list , Represents the number of list data
  • grammar :
len(list_name)
# Return a number 
name=['aaa','bbb','ccc']
print(len(name))
print(type(len(name)))
# 3
# <class 'int'>

Judge

Return value bit True perhaps False

  • in: Determine whether a list sequence exists in the specified data , In is true
  • not in: Judge that the specified data is not in a list sequence , No, it's true
  • grammar
 data in list_name
shuju1 not in list_name
name=['aaa','bbb','ccc']
print('aaa' in name)
print('aa' in name)
print('aa' not in name)
# True
# False
# True

increase

Add specified data to the list

  • append(): Append data to the end of the list
  • grammar :
list.append( data )
name=['aaa','bbb','ccc']
name.append('ddd')
print(name)
# ['aaa', 'bbb', 'ccc', 'ddd']

You can append the list sequence

name=['aaa','bbb','ccc']
name.append([11,22])
print(name)
# ['aaa', 'bbb', 'ccc', [11, 22]]

Pay attention to is , Only one data can be appended at a time , You cannot append multiple data at the same time

  • extend(): Add data at the end of the list
  • grammar
list.extend( data )

The difference between here and above is , When adding a sequence here , Will take the sequence apart

name=['aaa','bbb','ccc']
name.extend('ddd')
print(name)
# ['aaa', 'bbb', 'ccc', 'd', 'd', 'd']
# there ‘ddd’ It is also a sequence , So take it apart 
name=['aaa','bbb','ccc',12]
name.extend([10,13])
print(name)
# ['aaa', 'bbb', 'ccc', 12, 10, 13]
name=['aaa','bbb','ccc',12]
name.extend(10)
print(name)
# TypeError: 'int' object is not iterable
# int Not an iteratable type , Not directly extend
name=['aaa','bbb','ccc',12]
name.extend(range(1,2))
print(name)
# ['aaa', 'bbb', 'ccc', 12, 1]
  • insert(): Insert data in the specified location
  • grammar :
list.insert( Subscript , data )
name=['aaa','bbb','ccc',12]
name.insert(2,'ddd')
print(name)
# ['aaa', 'bbb', 'ddd', 'ccc', 12]

Here's what we have to pay attention to , The added part is actually added to the list itself , The data of the list itself has been modified , This and str Different types

Delete

  • del : It is worth noting that , If you visit here after deleting it, you will report an error
  • grammar :
del The goal is
del( The goal is )
# Delete data in the specified location 
del list[ Subscript ]
name=['aaa','bbb','ccc',12]
del name
print(name)
# NameError: name 'name' is not defined
name=['aaa','bbb','ccc',12]del name[0]print(name)# ['bbb', 'ccc', 12]
  • pop: Delete data in the specified location , If you do not specify the default, delete the last data ; No matter what data is deleted ,pop Will return the deleted data
  • grammar :
list.pop( Subscript )
name=['aaa','bbb','ccc',12]a=name.pop()print(name)print(a)# ['aaa', 'bbb', 'ccc']# 12

This method cannot delete multiple data

  • remove(): Delete the specified data
  • grammar :
list.remove( Specified data )
name=['aaa','bbb','ccc',12]name.remove(12)print(name)# ['aaa', 'bbb', 'ccc']
  • clear(): clear list , The result is an empty list , At the end of printing, there is an empty list , Instead of reporting a mistake
  • grammar :
list.clear()
name=['aaa','bbb','ccc',12]name.clear()print(name)# []

Deleting data is also deleted in the list itself

modify

  • Modify the following table at the specified location , Directly use the assignment statement
name=['aaa','bbb','ccc',12]name[0]='gdhhhr'print(name)# ['gdhhhr', 'bbb', 'ccc', 12]
  • reverse(): In reverse order
name=['aaa','bbb','ccc',12]name.reverse()print(name)# [12, 'ccc', 'bbb', 'aaa']
  • sort(): Sorting algorithm , The default is ascending sort
  • grammar :
list.sort(key=None,reverse=False)# key It is to sort according to a certain value in the dictionary ,reverse=False Expressing ascending order ,reverse=True Representation of descending order 
name=[1,2,3,4,6,7,5]name.sort()print(name)# [1, 2, 3, 4, 5, 6, 7]
name=[1,2,3,4,6,7,5]name.sort(reverse=True)print(name)# [7, 6, 5, 4, 3, 2, 1]

Copy

  • copy(): The copy function has a return value , Is the data after replication , It is generally used to retain source data

  • grammar :

list.copy()

Loop traversal of list

i=0name=[1,2,3,4,6,7,5]while i<len(name): print(name[i] ,end=' ') i+=1# 1 2 3 4 6 7 5
name=[1,2,3,4,6,7,5]for i in name: print(i,end=' ')# 1 2 3 4 6 7 5

List nesting

name=[[1,2,3],[23,34,45],[234,456,789]]for i in name: print(i,end=' ')# [1, 2, 3] [23, 34, 45] [234, 456, 789]
name=[[1,2,3],[23,34,45],[234,456,789]]for i in name: for j in i: print(j,end=' ')# 1 2 3 23 34 45 234 456 789

13、 ... and 、 Tuples tuple

Store multiple data , Data cannot be modified , Use parentheses

Get the data of a certain subscript :tuple[i]

Format

Use parentheses

name=(10,20)

What we should pay attention to here is , If the tuple defined has only one data , Add a comma after this data , Otherwise, the data type will be the only data type

name=(10)name1=(10,)print(type(name))print(type(name1))# <class 'int'># <class 'tuple'>

Common operations of tuples

Because tuples do not support modification , Only search operation is supported , So the operations here are all search operations

  • index(): If this data does not exist, an error will be reported
  • grammar
tuple.index(e,start,end)
a=(11,22,33,44)print(a.index(11))
  • count()

  • grammar :

tuple.count()
  • len()
  • grammar :
tuple.len()

modify

Nested lists in tuples , The contents of this list can be modified

fourteen 、 Dictionaries dict

  • The data of the dictionary appears in the form of key value pairs , The data of the dictionary is out of order , Subscript search data is not supported
  • The symbol of the dictionary is brace
  • Data is in the form of key value pairs
  • Each key value pair is separated by commas

Create a dictionary

a={
'name':'Tom','age':20,'gender':' male '}a=dict()a={
}

Dictionary common operation

Dictionaries are variable types , That is, the modification of the dictionary is based on the data of the dictionary itself , This year and list equally

increase

How to write it :dictName[key]=value

If key Modify as long as it exists value, If it does not exist, add this key value pair

a={
'name':'ccc','age':20}a['name']='cch'print(a)# {'name': 'cch', 'age': 20}
a={
'name':'ccc','age':20}a['id']=1print(a)# {'name': 'ccc', 'age': 20, 'id': 1}

Delete

  • del() Delete the dictionary or the specified key value pair
a={
'name':'ccc','age':20}del(a)print(a)# NameError: name 'a' is not defined
a={
'name':'ccc','age':20}del a['name']print(a)# {'age': 20}# If it doesn't exist, it will report an error 
  • clear()
a={
'name':'ccc','age':20}a.clear()print(a)# {}

Change

How to write it : Dictionary sequence [key]=value, In fact, it is no different from increasing

a={
'name':'ccc','age':20}a['name']='cch'print(a)# {'name': 'cch', 'age': 20}

check

  • key lookup , If key If it doesn't exist, it will report an error
a={
'name':'ccc','age':20}print(a['name'])# ccc
  • get(): If the current key Can't find or doesn't exist , The second parameter will be returned ( Which is the default value ), If the second parameter is omitted None
  • grammar
 Dictionary sequence .get(key, The default value is )
a={
'name':'ccc','age':20}
print(a.get('id',1))
# 1
  • keys(): Return all keys,keys What is returned is the object that can be iterated
a={
'name':'ccc','age':20}
print(a.keys())
# dict_keys(['name', 'age'])
  • values(): Returns all values of the current dictionary , It's also an iterable object
a={
'name':'ccc','age':20}
print(a.values())
# dict_values(['ccc', 20])
  • items(): Each key value pair is returned , It's also an iterable object , The data inside is a tuple
a={
'name':'ccc','age':20}
print(a.items())
# dict_items([('name', 'ccc'), ('age', 20)])

Traverse

Here I analyze unpacking

a={
'name':'ccc','age':20}
for key,value in a.items():
print(f'{
key}={
value}')
# name=ccc
# age=20

15、 ... and 、 aggregate set

Create set

  • To create a collection, you can use {} perhaps set(), But if you want to create an empty collection, you can only use set(), because {} Used to create an empty dictionary
  • Why you need to assemble : Because the collected data can be de duplicated , That is, there is no duplicate data in the data
  • There is no order in a set , Therefore, subscripts cannot be used
  • Sets are mutable types , That is, the modification is made in the original set
set1={
12,10,28,28,28}
print(set1)
# {10, 12, 28}
set2=set()
print(set2)
# set()
set1={
'abcfdhdjfdj'}
print(set1)
# {'abcfdhdjfdj'}
set2=set('qwert')
print(set2)
# {'q', 't', 'w', 'r', 'e'}
# There is no sequential output 

Common operation methods of collection

increase

  • add(): Add data , Because the set has the function of de duplication , Therefore, adding existing data will not take effect
set1={
12,23,45,2}
set1.add(10)
print(set1)
# {2, 10, 12, 45, 23}
set1={
12,23,45,2}
set1.add(10,11)
print(set1)
# TypeError: add() takes exactly one argument (2 given)
  • update(): What is appended is the sequence
set1={
12,23,45,2}
set1.update([10,11])
print(set1)
# {2, 10, 11, 12, 45, 23}

Delete

  • remove(): Delete the specified data , If the data does not exist, an error will be reported
set1={
12,23,45,2}
set1.remove(12)
print(set1)
# {2, 45, 23}
  • discard(): Delete the data assigned to in the set , The stock data does not exist and will not report an error , Just don't operate
set1={
12,23,45,2}
set1.discard(10)
print(set1)
# {2, 12, 45, 23}
  • pop(): Randomly delete a data , And return this data
set1={
12,23,45,2}
num=set1.pop()
print(set1)
print(num)
# {12, 45, 23}
# 2

lookup

  • in: Judge whether the data is in the set sequence
  • not in: Determine whether the data is not in the data
set1={
12,23,45,2}
print(10 in set1)
print(10 not in set1)
# False
# True

sixteen 、 Common operator

seventeen 、 Public methods

  • range(start,end,step), If there is only one data representation end, Then start from 0 Start , It doesn't contain end The location of
for i in range(10):
print(i)
# 0 1 2 3 4 5 6 7 8 9
  • enumerate(): The return result is a tuple , The first data of the tuple is the subscript of the original iterative data object , The second data is the data of the original iteration , And here's start Is the starting value of the subscript
  • grammar
enumerate( Traversable objects ,start=0)
# start Parameter is used to set the subscript starting value of data , The default is 0
list1=[1,2,3,4,5,6]
for i in enumerate(list1):
print(i,end=" ")
# (0, 1) (1, 2) (2, 3) (3, 4) (4, 5) (5, 6)
  • This example illustrates the subscript from 1 Start iteration
list1=[1,2,3,4,5,6]
for i in enumerate(list1,1):
print(i,end=" ")
# (1, 1) (2, 2) (3, 3) (4, 4) (5, 5) (6, 6)

eighteen 、 Container type conversion

  • tuple(): Transform data into meta groups

  • list(): Turn data into lists

  • set(): Transform data into collections , You can get rid of it

nineteen 、 The derived type

stay python in , Only list 、 Dictionaries 、 Only set has derivation

Derivation is also called generative

The derivation is used to simplify the code .

List derivation

= effect : Create a with an expression A regular list Or control a regular list .=

  • What is particularly noteworthy here is , The rule here is that the content of the list is regular .

  • List derivation is also called list generation

  • demand : Generate a regular list

Here is the conventional way of writing

list1=[]
i=0
while i<10:
list1.append(i)
i+=1
print(list1)
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Here is a demonstration of the implementation of a derivation

list1=[i for i in range(10)]
print(list1)
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

belt if List derivation of

demand : establish 0-10 Even list of

  • Use range() Step size implementation
list1=[i for i in range(0,10,2)]
print(list1)
# [0, 2, 4, 6, 8]
  • Use if Realization
list1=[i for i in range(0,10) if i%2==0]
print(list1)
# [0, 2, 4, 6, 8]

Multiple for Loop to implement the list derivation

demand : Create the following list :

[(1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
  • Conventional writing :
list2=[]
for i in range(1,3):
for j in range(3):
list2.append((i,j))
print(list2)
  • The derived type
list1=[(i,j) for i in range(1,3) for j in range(3)]
print(list1)

Dictionary derivation

The function of dictionary derivation : Quickly merge two lists into one dictionary

  • Create a key yes 1-5 The number of ,value It's the half of this number
dict1={
i:i**2 for i in range(1,5)}
print(dict1)
# {1: 1, 2: 4, 3: 9, 4: 16}
  • Merge the two lists into one dictionary
list1=[1,2,3]
list2=[1,4,9]
dict2={
list1[i]:list2[i] for i in range(len(list1))}
print(dict2)
# {1: 1, 2: 4, 3: 9}
  • What happens when the data length of the list is inconsistent
list1=[1,2,3]list2=[1,4]dict2={
list1[i]:list2[i] for i in range(len(list1))}print(dict2)
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-14-96a775aca203> in <module>
1 list1=[1,2,3]
2 list2=[1,4]
----> 3 dict2={list1[i]:list2[i] for i in range(len(list1))}
4 print(dict2)
<ipython-input-14-96a775aca203> in <dictcomp>(.0)
1 list1=[1,2,3]
2 list2=[1,4]
----> 3 dict2={list1[i]:list2[i] for i in range(len(list1))}
4 print(dict2)
IndexError: list index out of range

So we should notice here , If the length of two lists is the same , You can take it at will list1 perhaps list2 The length of , The results are the same , But if the length is inconsistent , Take the length of the data in the list with a shorter length , Otherwise, an error will be reported

  • Extract the target data from the dictionary

Normal problem solving ideas :

counts={
'MBP':258,'HP':20,'LENOVO':199}
count1={
}
for key,value in counts.items():
if value>100:
count1[key]=value
print(count1)

The derived type :

counts={
'MBP':258,'HP':20,'LENOVO':199}count1={
key:value for key,value in counts.items() if value>100}print(count1)

result :

{'MBP': 258, 'LENOVO': 199}

Set derivation

demand : Create a collection , Data bit list data 2 Power , What we should pay attention to here is ,set It has the effect of weight removal

list1=[1,1,2]set1={
i**2 for i in list1}print(set1)# {1,4}

twenty 、 function

python in , Functions must be defined before use

Format

def Function name ( Parameters ):
Code 1
Code 2
...

The return value of the function is in python There is no need to write the return value in front of the function name in , direct return That's all right.

Function documentation

Check the function description document

help( Function name )

Define the documentation : If and only if it can only be indented in the first line of the function and written in the form of multi line comments, it can be regarded as a description document

  • Here is an example
def delSameListElement(List1,temp):
""" Define a function , It means to delete duplicate data in a list . It uses a temp Come and take list Of non duplicate data . """
for i in List1:
if i in temp:
continue
else:
temp.append(i)
return 0;
temp=[]
List1 = [0, 1, 2, 3, 4, 1,1]
delSameListElement(List1,temp)
print(temp)
help(delSameListElement)
  • Result display
[0, 1, 2, 3, 4]Help on function delSameListElement in module __main__:delSameListElement(List1, temp) Define a function , It means to delete duplicate data in a list . It uses a temp Come and take list Of non duplicate data .

The return value of the function

The return value of the function mentioned here is for the case that the function has multiple return values .

If there are more than one return Value , A tuple is returned ,return You can also return to the list 、 Tuples 、 Dictionary, etc

def return_num(): return 1,2num1=return_num()print(num1)# (1, 2)

Parameters

Positional arguments

It is basically no different from our normal parameters , That is, when the function is called , The order of parameters should be consistent with the order of the function itself , Otherwise, it will report a mistake

Key parameters

Function call , adopt ” key = value “ In the form of , It can make the function clearer , And easier to use , also The need to clear the order of parameters

def return_num(name,age,gender): print(f' name :{
name}, Age :{
age}, Gender :{
gender}')return_num('Rose',gender=' Woman ',age=20)# name :Rose, Age :20, Gender : Woman 

When the function is called , If there are position parameters , Positional parameters must be in the face of keyword parameters , However, there is no sequence between keyword parameters

Default parameters

Default parameters are also called default parameters , To define a function , Provide default values for functions , You can call a function without passing the value of the default parameter ( Be careful : All position parameters must also appear in front of the default parameter value , Including the definition and call of functions )

def return_num(name,age,gender=' male '): print(f' name :{
name}, Age :{
age}, Gender :{
gender}')return_num('Tom',age=20)return_num('Rose',age=20,gender=' Woman ')
 name :Tom, Age :20, Gender : Male name :Rose, Age :20, Gender : Woman

When the function is called , If it defaults, it will call the default value directly

Indefinite length parameter

Also called variable parameter , It is used to determine how many parameters need to be passed when calling , It's time to With parcels (packing) Positional arguments , Or package keyword parameters , To pass parameters , It will be very convenient .

  • Package location delivery - Use *args
def return_num(*args): print(args)return_num('Tom',10)return_num('Rose',20,' Woman ')
('Tom', 10)('Rose', 20, ' Woman ')

The parameters passed in will be args Variable collection , It will be combined into a tuple according to the position of the passed parameters , This is the package location transfer

  • Package keyword delivery
def return_num(**kwargs):
print(kwargs)
return_num(name='Tom',age=10)
{'name': 'Tom', 'age': 10}

Finally, a dictionary type is returned

Whether it is package bit transfer or package keyword transfer , It's all a packaging process

unpacking

  • Tuple unpacking
def return_num():
return 100,200 # What is returned here is a tuple 
num1,num2=return_num()
print(num1)
print(num2)
100
200
  • Dictionary unpacking
dict1={
'name':'Tom','age':10}
a,b=dict1 # What comes out is keys
print(a)
print(b)
print(dict1[a])
print(dict1[b])
nameageTom10

Exchange variable values

  • Use the third variable to store data ,java Regular use
  • Direct exchange
a,b=1,20
a,b=b,a
print(a,b)
# 20 1

The 21st 、 quote

stay python in , Values are passed by reference

We can use id() To determine whether two variables are references to the same value , We can talk about id It is understood as the identification of the address of that memory

  • Immutable type
a=1
b=a
print(id(a))
print(id(b))
a=2
print(b)# explain int Type is immutable data 
print(id(a))
print(id(b))
140712497063728
140712497063728
1
140712497063760
140712497063728

We can understand it this way , Every time we define a data , Will open up a memory , A variable is a reference to the address of this data .

int Data of type is immutable

  • Variable type
aa=[11,22]bb=aaprint(id(aa))print(id(bb))aa.append(33)print(id(aa))print(id(bb))
2325297783432
2325297783432
2325297783432
2325297783432

Reference as argument

It is normal to pass variables to the function call

Twenty-two 、 Variable and variable types

  • Variable type
    • list
    • Dictionaries
    • aggregate
  • Immutable type
    • plastic
    • floating-point
    • character string
    • Tuples

23 、 recursive

Learned to omit

Twenty-four 、lambda expression

and java The same as , When a function has a return value , And there's only one code , have access to lambda

expression

grammar

Here's what's interesting :

  • The expression must have a return value
  • Parameter list is optional
lambda parameter list : expression

Experience cases

  • No parameter
def fn1():
return 200
print(fn1)
print(fn1())
fn2=lambda:100
print(fn2)
print(fn2())
<function fn1 at 0x00000229F25F4280>
200
<function <lambda> at 0x00000229F1A14F70>
100
  • With parameters
def fn1(a,b): return a+bprint(fn1(1,2))fn2=lambda a,b:a+bprint(fn2(1,2))
33
  • Default parameters
def fn1(a,b,c=100): return a+b+cprint(fn1(1,2))fn2=lambda a,b,c=100:a+b+cprint(fn2(1,2))
103103
  • Variable parameters *args
def fn1(*args):
return args
print(fn1(1,2))
fn2=lambda *args:args
print(fn2(1,2))
(1, 2)
(1, 2)
def func(a,*b):
for item in b:
a += item# unpacking 
return a
m = 0
print(func(m,1,1,2,3,5,7,12,21,33))
# 85
  • Variable parameters *kwargs
def fn1(**kwargs):
return kwargs
dict1=fn1(name='Tom',age=20)
print(dict1)
fn2=lambda **kwargs:kwargs
print(fn2(name='Rose',age=10))
{'name': 'Tom', 'age': 20}{'name': 'Rose', 'age': 10}

lambda application

With judgment lambda

fn1=lambda a,b:a if a>b else bprint(fn1(1,290))# 290

List data according to dictionary key Sort

students=[{
'name':'Tom','age':10},{
'name':'Rose','age':20},{
'name':'Jack','age':30}]# according to name Sort values in ascending order students.sort(key=lambda x:x['name'])print(students)# according to name null students.sort(key=lambda x:x['name'],reverse=True)print(students)
[{'name': 'Jack', 'age': 30}, {'name': 'Rose', 'age': 20}, {'name': 'Tom', 'age': 10}][{'name': 'Tom', 'age': 10}, {'name': 'Rose', 'age': 20}, {'name': 'Jack', 'age': 30}]

twenty-five 、 Built in higher order function

Pass in the function as an argument , Such functions are called higher-order functions , Higher order function is the embodiment of functional programming .

abs- It's not a higher-order function

Find the absolute value of the number

round- It's not a higher-order function

Round the function

print(round(1.5))# 2

map function

  • ==map(func,list)== yes Python Built in higher-order functions , It receives a function func And a list, And by putting the function func Acting in turn list On each element of , Get a new one list(python2) Or iterators (python3) And back to .
# The function of this is to change the data in the list into its square value def f(x): return x*xprint(list(map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])))# [1, 4, 9, 10, 25, 36, 49, 64, 81]

Be careful :

  • because list The contained elements can be of any type , therefore ,map() It's not just about dealing with numbers list, In fact, it can handle any type of list, Just pass in the function f Can handle this data type .

reduce function

  • reduce(func,list) among func There have to be two parameters , every time func The calculation result of continues to accumulate with the next element of the sequence
import functools
list1=[1,2,3,4]
def fun(a,b):
return a+b
result=functools.reduce(fun,list1)
print(result)
# 10
import functools
list1=[1,2,3,4]
def fun(a,b):
return a-b
result=functools.reduce(fun,list1)
print(result)
# -8

filter function

  • filter(func,list) Function is used to filter out unqualified elements , Return to one filter object , Here objects can be converted to other data types, such as list
list1=[1,2,3,4,5,6,79.7]
def fun(x):
return x%2==0
result=filter(fun,list1)
print(result)
print(list(result))
<filter object at 0x000002011BE270A0>[2, 4, 6]

zip function

  • The function prototype :zip(*iterables), Parameters of variable length can be passed

  • This function takes a series of lists as parameters , Package the corresponding elements in the list into tuples , Then return a list of these tuples .

eval function

  • eval(< character string >) Be able to Python Parse and execute the string as an expression , And output the returned results .

  • eval The() function converts an input string to Python sentence , And execute the statement

hexacosa- 、 File operations

The basic operation of the file

  1. Open file
  2. Read, write, etc
  3. Close file

open

Use open function , You can open an existing file , Or if the file does not exist, you can create a new file

 object =open(name,mode)

name: Is the string of the target file name to open ( It can contain the specific path where the file is located )

mode: Set the mode to open the file ( Access pattern ): read-only 、 write in 、 Supplemental

Quick experience

f=open('test.txt','w')f.write('cch')f.close()

Access pattern

r: read-only , If the file does not exist, an error will be reported ,r Nor does it support writing , because r Read only

w: Write , If the file doesn't exist , Will create a new file ; If the file exists , Will edit from scratch , That is, the original content will be overwritten

a: Additional , If the file exists, append , If the file does not exist, it will be created and written

If the access mode is omitted , Indicates that the file is read-only (r)

with b Of : Represents binary file form

with + Of : Indicates readable and writable mode

Understanding of prefix : The following additions are based on the prefix pattern to expand , Must meet the conditions of prefix requirements

The file pointer :r and w Are at the beginning of the file ,a It's at the end of the file

f=open('test.txt','r')a=f.read()print(a)f.close()
cch
f=open('test.txt','a')f.write('cch')f.close()# cchcch

read

  • read()
 File object .read(num)# num Indicates the length of data read from the file ( Unit is byte ), If no incoming num, Means to read all the contents 
#txt The content in I can't conceivable that the number of suicies has reached 30-year high in American
f=open('test.txt','r')a=f.read(10)print(a)f.close()#I can't co# Here's what's interesting , Spaces also occupy one byte 
  • readlines()

You can read the contents of the whole file at one time in line , And it returns a list , The data in each row is an element , And return the newline symbol together and print it

f=open('test.txt','r')a=f.readlines()print(a)f.close()
["I can't conceivable that the number of suicies has reached 30-year high in American\n", 'brilliance\n', 'universal\n', 'ultimate']
  • readline()

By default, the first line is read for the first time , Read the second line for the second time , And so on

f=open('test.txt','r')a=f.readline()print(a)a=f.readline()print(a)f.close()
I can't conceivable that the number of suicies has reached 30-year high in Americanbrilliance

Move the pointer position

  • seek()

effect : Used to move the file pointer

 File object .seek( Offset , The starting position )

The starting position :

  • 0: Beginning of file
  • 1: The current position
  • 2: End of file
  • start
f=open('test.txt','r')
f.seek(2,0)
a=f.read()
print(a)
f.close()

This example represents , Start at the beginning , The offset 2 Bit, that is, the first two cannot be , Everything else can be read

can't conceivable that the number of suicies has reached 30-year high in American
brilliance
universal
ultimate
  • ending
f=open('test.txt','r')
f.seek(0,2)
a=f.read()
print(a)
f.close()

twenty-seven 、 object-oriented

Object orientation is to treat programming as a transaction , For the outside world , Transactions are used directly , Don't worry about his internal situation , Programming is to set what a transaction can do

Twenty-eight 、 Classes and objects

Define a class and object

  • Create classic classes

The class name follows the naming habit of the big hump

class Class name :
...
  • Create new classes
  • This default is inheritance object class , But it can be modified
class Class name (object):
...
  • Create objects
 Object name = Class name ()
  • example
# Define a class 
class Wahser():
def wash(self):
print(' Wash the clothes ing...')
# Define an object 
haier=Wahser()
haier.wash()
# Wash the clothes ing...

self

self Refers to the object that calls this function

# Define a class 
class Wahser():
def wash(self):
print(' Wash the clothes ing...')
print(self)
# Define an object 
haier=Wahser()
print(haier)
haier.wash()
<__main__.Wahser object at 0x00000204C2298D00>
Wash the clothes ing...
<__main__.Wahser object at 0x00000204C2298D00>

Add or get attributes

The properties of the object can be added outside the class , You can also add access to classes

Add and get object properties outside the class

# add to
Object name . Property name = value
# obtain
Object name . Property name
# Define a class 
class Wahser():
def wash(s):
print(' Wash the clothes ing...')
# Define an object 
haier=Wahser()
haier.width=500
haier.higth=600
print(f' Width {
haier.width}, Height {
haier.higth}')
haier.wash()
 Width 500, Height 600
Wash the clothes ing...

Get the object properties in the class -self

The important thing to note here is that , The properties here must be defined before calling

self. Property name
# Define a class 
class Wahser():
def wash(self):
print(' Wash the clothes ing...')
print(f' Width {
self.width}, Height {
self.higth}')
# Define an object 
haier=Wahser()
haier.width=500
haier.higth=600
haier.wash()
 Wash the clothes ing...
Width 500, Height 600

Magic methods

stay python in ,_xx_() The function of is called magic method , Refers to functions with special functions

—init—()

  • This is used to initialize objects , It can be used to set properties in the class itself
  • —init—() Method is called by default when creating an object , There is no need to manually call
  • —init—(self) Medium self Parameters of , No need for developers to deliver ,python The interpreter will automatically pass the current object
# Define a class 
class Wahser():
def __init__(self) :
self.width=500
self.height=800
def info(self):
print(f' Width {
self.width}, Height {
self.height}')
def wash(self):
print(' Wash the clothes ing...')
# Define an object 
haier=Wahser()
haier.info()
haier.wash()
 Width 500, Height 800
Wash the clothes ing...

Parameterized —init—(self)

# Define a class 
class Wahser():
def __init__(self,width,height) :
self.width=width
self.height=height
def info(self):
print(f' Width {
self.width}, Height {
self.height}')
def wash(self):
print(' Wash the clothes ing...')
# Define an object , Because it has been called when the object is created __init__ Method 
haier=Wahser(100,200)
haier.info()
haier.wash()
 Width 100, Height 200
Wash the clothes ing...

—str—(self)

When print When choosing which one , We will print out the memory address by default , But if the class defines this method, it will print out the contents of this method return The data of

# Define a class 
class Wahser():
def __init__(self,width,height) :
self.width=width
self.height=height
def __str__(self) -> str:
return ' Here is the instructions of the mailbox ...'
def info(self):
print(f' Width {
self.width}, Height {
self.height}')
def wash(self):
print(' Wash the clothes ing...')
# Define an object 
haier=Wahser(100,200)
print(haier)
haier.info()
haier.wash()
 Here is the instructions of the mailbox ...
Width 100, Height 200
Wash the clothes ing...

—del—(self)

When deleting objects ,python Call this method automatically

# Define a class 
class Wahser():
def __init__(self,width,height) :
self.width=width
self.height=height
def __str__(self) -> str:
return ' Here is the instructions of the mailbox ...'
def __del__(self):
print(' Object has been deleted ')
def info(self):
print(f' Width {
self.width}, Height {
self.height}')
def wash(self):
print(' Wash the clothes ing...')
# Define an object 
haier=Wahser(100,200)
print(haier)
haier.info()
haier.wash()
del haier
 Here is the instructions of the mailbox ...
Width 100, Height 200
Wash the clothes ing...
Object has been deleted

Inherit

# Define a parent class animal
class animal():
def __init__(self,name) :
self.name=name# Animals have names 
def info(self):
print(f' This is {
self.name}')
# Define a subclass 
class dogs(animal):
pass
dog=dogs('dog')
dog.info()
# This is dog

Single inheritance

  • A parent class has only one subclass, which is single inheritance , above animal and dogs Is single inheritance

Multiple inheritance

  • A subclass has more than one parent
  • When a class has more than one parent class , By default, the properties and methods with the same name of the first parent class are used

rewrite

  • Subclasses can override methods and properties with the same name as the parent class , When calling methods and properties with the same name , The parent class will be overwritten by the child class

  • How subclasses call methods and properties with the same name of the parent class
# Define a parent class animal
class Animals():
def __init__(self) :
self.name=' animal '# Animals have names 
def info(self):
print(f' This is {
self.name}')
# Define a subclass 
class Dogs(Animals):
def __init__(self) :
self.name=' Dog '# Animals have names 
def info(self):
print(f' This is {
self.name}')
def make_Dogs(self):
# If you call the parent class properties and methods first , The attribute of the parent class will override the attribute of the child class , So before calling properties , First call your own subclass to initialize 
self.__init__()
self.info()
def make_Animals(self):
# Call the superclass method , But in order to ensure that the property called is also the property of the parent class , So you must call the initialization of the parent class before calling the method 
Animals.__init__(self)
Animals.info(self)
dog=Dogs()
dog.make_Dogs()
dog.make_Animals()
# This is a dog 
# This is an animal 

Multiple inheritance

Allow multiple levels of inheritance , As long as there is inheritance , Subclasses can call methods and properties of all parent classes

View inheritance relationships

 Class name .__mro__
print(dogs.__mro__)
#(<class '__main__.dogs'>, <class '__main__.animal'>, <class 'object'>)

super()

# With parameters
super( The class name of the current class ,self). Method of the same name
# No parameter
super(). Method of the same name
  • Used to call the parent method
  • In fact, it is equivalent to using the parent class to override the child class
  • In multi-layer inheritance , If you want to call a method with the same name in the parent class of the parent class , Just use it in the immediate parent class super Grammar is OK

Here is a demonstration with parameters

# Define a parent class animal
class Animals():
def __init__(self) :
self.name=' animal '# Animals have names 
def info(self):
print(f' This is {
self.name}')
# Define a subclass 
class Dogs(Animals):
def __init__(self) :
self.name=' Dog '# Animals have names 
def info(self):
print(f' This is {
self.name}')
def make_Dogs(self):
super(Dogs,self).__init__()
super(Dogs,self).info()
# def make_Dogs(self):
# # If you call the parent class properties and methods first , The attribute of the parent class will override the attribute of the child class , So before calling properties , First call your own subclass to initialize 
# self.__init__()
# self.info()
# def make_Animals(self):
# # Call the superclass method , But in order to ensure that the property called is also the property of the parent class , So you must call the initialization of the parent class before calling the method 
# Animals.__init__(self)
# Animals.info(self)
dog=Dogs()
dog.make_Dogs()
# dog.make_Animals()
# This is an animal 

What is demonstrated here is parameterless

# Define a parent class animal
class Animals():
def __init__(self) :
self.name=' animal '# Animals have names 
def info(self):
print(f' This is {
self.name}')
# Define a subclass 
class Dogs(Animals):
def __init__(self) :
self.name=' Dog '# Animals have names 
def info(self):
print(f' This is {
self.name}')
def make_Dogs(self):
super().__init__()
super().info()
# def make_Dogs(self):
# # If you call the parent class properties and methods first , The attribute of the parent class will override the attribute of the child class , So before calling properties , First call your own subclass to initialize 
# self.__init__()
# self.info()
# def make_Animals(self):
# # Call the superclass method , But in order to ensure that the property called is also the property of the parent class , So you must call the initialization of the parent class before calling the method 
# Animals.__init__(self)
# Animals.info(self)
dog=Dogs()
dog.make_Dogs()
# dog.make_Animals()

Private property

  • Set some properties or methods so that they are not inherited by subclasses

  • How to set private properties : Precede the property name and method name with two underscores

# Define a parent class animal
class Animals():
def __init__(self) :
self.__skin=' Hair '# This is a private property 
self.name=' animal '# Animals have names 
def info(self):
print(f' This is {
self.name}')
# Define a subclass 
class Dogs(Animals):
def __init__(self) :
self.name=' Dog '# Animals have names 
def info(self):
print(f' This is {
self.name}')
def make_Dogs(self):
super().__init__()
super().info()
dog=Dogs()
dog.make_Dogs()
print(dog.__skin)
 This is an animal
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-18-ba391c645d4c> in <module>
20 dog=Dogs()
21 dog.make_Dogs()
---> 22 print(dog.__skin)
AttributeError: 'Dogs' object has no attribute '__skin'

Get and modify private properties

Private attributes cannot be inherited , But it can be passed in the class get_xx( Get private properties ) and set_xx( Modify private properties )

# Define a parent class animal
class Animals():
def __init__(self) :
self.__skin=' Hair '# This is a private property 
self.name=' animal '# Animals have names 
def info(self):
print(f' This is {
self.name}')
def get_skin(self):
return self.__skin
def set_skin(self,skin):
self.__skin=skin
# Define a subclass 
class Dogs(Animals):
pass
dog=Dogs()
dog.set_skin(' Brown hair ')
print(dog.get_skin())
# Brown hair 

encapsulation

  • Write properties and methods to classes

polymorphic

stay python in , Polymorphism does not necessarily come from inheritance , But the best source is inheritance

  • Polymorphism is a way of using objects , Subclasses override methods of the parent class , Call the same parent method of different subclass objects , Different execution results can be produced
class Dog(object):
def work(self):
pass
class DrugDog(Dog):
def work(self):
print(' Trace drugs ')
class ArmyDog(Dog):
def work(self):
print(' Track down the prisoners ')
class Persion(object):
def work_with_dog(self,dog):
dog.work()
persion =Persion()
dog=ArmyDog()
persion.work_with_dog(dog)
dog=DrugDog()
persion.work_with_dog(dog)
 Track down the prisoners
Trace drugs

Class properties and instance properties

Class properties

  • Class properties are properties owned by class objects , It is public to all instance objects of this class

  • Class properties can be accessed using class objects or instance objects

# Define a class animal
class Animals():
tooth=10# Class properties 
print(Animal.tooth)# Such access 
cat=Animals()
print(cat.tooth)# Instance access 
dog=Animals()
print(dog.tooth)
#10
#10
#10

Modify class properties

Class attributes can only be modified through classes , Cannot be modified by an instance object , If you have heard of instance object modification , This means that an instance attribute is created

# Define a class animal
class Animals():
tooth=10# Class properties 
Animals.tooth=14
print(Animals.tooth)
cat=Animals()
print(cat.tooth)
dog=Animals()
dog.tooth=20# Created an instance property tooth=20
print(cat.tooth)
print(dog.tooth)
14
14
14
20

Class methods and static methods

Class method

  • Decorator required @classmethod It is class methods that are identified , For class methods , The first parameter must be a class object , General one cls As the first parameter
  • Class methods are generally used with class attributes
# Define a class animal
class Animals():
__tooth=10# Class properties 
@classmethod
def get_tooth(cls):
return cls.__tooth
cat=Animals()
result=cat.get_tooth()
print(result)
#10

Static methods

  • Static methods require decorators @staticmethod To decorate , Static methods do not need to pass class objects or 1 Instance object ( No formal parameters self、cls)
  • Static methods can also be accessed through instance objects and class objects
# Define a class animal
class Animals():
@staticmethod
def get_static():
print(' Static methods ')
cat=Animals()
cat.get_static()
Animals.get_static()
 Static methods
Static methods

Twenty-nine 、 abnormal

try:
The code that could have an error
except:
If there is an exception to the execution of the code
try:
f=open('test1.txt','r')
except:
f=open('test1.txt','w')

Catch the specified exception

try:
The code that could have an error
except ( Exception types 1, Exception types 2) as result:
print(result)# Print the information of the captured exception 

Be careful :

  1. If the exception type of the code you are trying to execute is not the same as the type you want to catch , There is no way to catch exceptions
  2. In general try There is only one line of code below

Catch all exceptions

Exception Is the parent of all program exceptions

try:
The code that could have an error
except Exception as result:
print(result)# Print the information of the captured exception 

else

else Indicates the code to be executed if there is no exception

try:
The code that could have an error
except Exception as result:
print(result)# Print the information of the captured exception 
else:
There is no exception code block to execute

finally

finally Indicates the code to be executed regardless of whether it is abnormal or not . For example, closing a file

try:
The code that could have an error
except Exception as result:
print(result)# Print the information of the captured exception 
else:
There is no exception code block to execute
finally:
Code block to be executed no matter whether it is abnormal or not

Custom exception

stay python in , The syntax for throwing custom exceptions is raise Exception object

# Customize an exception class , Inheritance Exceptipon
class shortInputError(Exception):
def __init__(self,length,min_len ) :
self.length=length
self.min_len=min_len
def __str__(self) :
return f' The length you entered is {
self.length}, No less than {
self.min_len} Characters '
def main():
try:
con=input(' Please input a password :')
if len(con)<8:
raise shortInputError(len(con),8)
except Exception as result:
print(result)
else:
print(' The password is entered correctly ')
main()

thirty 、 modular

Guide module mode

  • import Module name
import time
time. function
import time
print(time.time())
  • from Module name import Function name
from time import time
Direct function call
from time import time
print(time())
  • from Module name import*
from time from *
Direct function call
from time import *
print(time())
  • import Module name as Alias
  • from Module name import Function name as Alias
from time import time as t
print(t())

Sequence of module positioning

When importing a module ,python The order in which the parser searches for modules is :

  1. Current directory
  2. If not in the current directory ,python Just search shell Variable PYTHONPATH Every directory under ( The installation directory )
  3. If you can't find it ,python You will see the default path

Be careful :

  1. It is better not to duplicate your own file name with the existing module name , Otherwise, the existing modules will be unusable ( Because the search path goes from near to far )
  2. If from Module name import function , If the function name is repeated , What is called is the last defined or imported function
  3. Here's what's interesting , Even variables with the same name , It will also cover the module , Because our content is through quote To define the , When our names are the same , That is, the reference is the same , It will cause the later things to cover the original things , So when we define the name, we must pay attention not to have the same name as the module

—all—

If there is this variable in a module file , When using from xxx import * When you import it , Only elements in this list can be imported , Here's what's interesting , The name of this module , Only with .py Name the suffix , It cannot be named after any other suffix

__all__=['testA']
def testA():
print('testA')
def testB():
print('testB')
from module1 import *
testA()
testB()
testA
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-10-5967f3f88564> in <module>
1 from module1 import *
2 testA()
----> 3 testB()
NameError: name 'testB' is not defined

Thirty-one 、 package

Packages organize linked modules , That is, put it in the same folder , And create a folder named __init__.py file , Then this folder is called package

Create a package

  • Create a mypackage package
  • establish __init__.pymodule1.pymodule2.py file
  • Write code
def module1_test():
print(' This is module1 Method ')
def module2_test():
print(' This is module2 Method ')

Import package

  • Method 1
import Package name . Module name
Package name . Module name . The goal is
import mypackage.module1
mypackage.module1.module1_test()
  • Method 2
    Be careful : Must be in __init__.py Add... To the file __all__=[], Controls the list of modules that are allowed to be imported , If not set , It means that all modules cannot pass
from Package name impor*
Module name . The goal is
# Control the import behavior of the package 
__all__=['module1']
from mypackage import*
module1.module1_test()
 This is module1 Method

Thirty-two 、 Other intellectual

—dict—

  • Class or instance object
  • Used to collect class object or instance object properties 、 Method and the corresponding value , To return a dictionary
class Dog(object):
a=1
def work(self):
print(' I am working ')
dog=Dog()
print(Dog.__dict__)
{
'__module__': '__main__', 'a': 1, 'work': <function Dog.work at 0x00000270150CA790>, '__dict__': <attribute '__dict__' of 'Dog' objects>, '__weakref__': <attribute '__weakref__' of 'Dog' objects>, '__doc__': None}

python The date and time of

  • Python Provides a time and calendar Module can be used to format date and time .
  • The time interval is a floating-point decimal in seconds .
  • Every time stamp comes from 1970 year 1 month 1 Japan ( Epoch ) How long does it take to express
  • Python Of time There are many functions under the module that can convert common date formats . Such as function time.time() Used to get the current timestamp ,
import time
ticks=time.time()
print (" The current time is :",ticks)
# The current time is : 1634655386.6290803

time tuples

quite a lot Python Functions are assembled in one element 9 Group digital processing time :

Serial number Field value 04 Digit year 20081 month 1 To 122 Japan 1 To 313 Hours 0 To 234 minute 0 To 595 second 0 To 61 (60 or 61 It's leap seconds )6 What day of the week 0 To 6 (0 It's Monday )7 The day of the year 1 To 366 ( Julian calendar )8 Daylight saving time -1, 0, 1, -1 It's the flag that decides if it's daylight time

That is struct_time Tuples . This structure has the following properties :

Serial number attribute value 0tm_year20081tm_mon1 To 122tm_mday1 To 313tm_hour0 To 234tm_min0 To 595tm_sec0 To 61 (60 or 61 It's leap seconds )6tm_wday0 To 6 (0 It's Monday )7tm_yday1 To 366( Julian calendar )8tm_isdst-1, 0, 1, -1 It's the flag that decides if it's daylight time

Get the current time

import time
localtime = time.localtime(time.time())
print (" The local time is :", localtime)
 The local time is : time.struct_time(tm_year=2021, tm_mon=10, tm_mday=19, tm_hour=23, tm_min=0, tm_sec=35, tm_wday=1, tm_yday=292, tm_isdst=0)

Get the formatted time

You can choose various formats according to your needs , But the simplest function to get a readable time pattern is asctime():

import time
localtime = time.asctime( time.localtime(time.time()) )
print (" The local time is :", localtime)
# The local time is : Tue Oct 19 23:03:06 2021

Format date

time.strftime(format[, t])

import time
# Format as 2016-03-20 11:45:39 form 
print (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) )
# Format as Sat Mar 28 22:24:24 2016 form 
print(time.strftime("%a %b %d %H:%M:%S %Y", time.localtime()) )
# Convert format string to timestamp 
a = "Sat Mar 28 22:24:24 2016"
print (time.mktime(time.strptime(a,"%a %b %d %H:%M:%S %Y")))
2021-10-19 23:07:24
Tue Oct 19 23:07:24 2021
1459175064.0

python Medium time date format symbol :

  • %y Two digit year representation (00-99)
  • %Y Four digit year representation (000-9999)
  • %m month (01-12)
  • %d One day in the month (0-31)
  • %H 24 Hours in hours (0-23)
  • %I 12 Hours in hours (01-12)
  • %M Minutes (00-59)
  • %S second (00-59)
  • %a Local simplified week name
  • %A Local full week name
  • %b Local simplified month name
  • %B Local full month name
  • %c Local corresponding date and time representation
  • %j One day in the year (001-366)
  • %p Local A.M. or P.M. The equivalent of
  • %U Weeks of the year (00-53) Sunday is the beginning of the week
  • %w week (0-6), Sunday is the beginning of the week
  • %W Weeks of the year (00-53) Monday is the beginning of the week
  • %x Local corresponding date representation
  • %X Local corresponding time representation
  • %Z Name of the current time zone
  • %% % The sign itself

Get the calendar of a month

import calendar
cal = calendar.month(2016, 1)
print (" The following output 2016 year 1 Calendar of the month :")
print (cal)
 The following output 2016 year 1 Calendar of the month :
January 2016
Mo Tu We Th Fr Sa Su
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31

Time modular

Time The module contains the following built-in functions , There is time to deal with , There are also time format conversion :

Serial number Functions and descriptions 1time.altzone The number of offset seconds to return to the daylight saving time area in Western Greenwich . If the region is east of Greenwich, it will return a negative value ( Western Europe , Including the United Kingdom ). Enable region for daylight saving time to use .2[time.asctime(tupletime]) Accepts a time tuple and returns a readable form as "Tue Dec 11 18:07:14 2008"(2008 year 12 month 11 Japan Tuesday 18 when 07 branch 14 second ) Of 24 Character string .3time.clock( ) The number of seconds in floating-point count to return the current CPU Time . Used to measure the time consumption of different programs , Than time.time() More useful .4[time.ctime(secs]) The effect is equivalent to asctime(localtime(secs)), Parameter not given is equivalent to asctime()5[time.gmtime(secs]) Receive timestamp (1970 Floating point seconds after the era ) And return the time tuple in Greenwich astronomical time t. notes :t.tm_isdst Always be 06[time.localtime(secs]) Receive timestamp (1970 Floating point seconds after the era ) And return time tuple under local time t(t.tm_isdst Take 0 or 1, It depends on whether it's summer time or not ).7time.mktime(tupletime) Accept the time tuple and return the timestamp (1970 Floating point seconds after the era ).8time.sleep(secs) Delay calling thread ,secs Is the number of seconds .9[time.strftime(fmt,tupletime]) Receive in time tuples , And returns the local time in a readable string , Format by fmt decision .10time.strptime(str,fmt=’%a %b %d %H:%M:%S %Y’) according to fmt The format parses a time string into a time tuple .11time.time( ) Returns the timestamp of the current time (1970 Floating point seconds after the era ).12time.tzset() According to environment variable TZ Reinitialize time related settings .

Time The module contains the following 2 A very important attribute :

Serial number Properties and descriptions 1time.timezone attribute time.timezone It's the local time zone ( Daylight saving time not started ) Offset seconds from Greenwich (>0, America <=0 Most of Europe , Asia , Africa ).2time.tzname attribute time.tzname Contains a pair of strings that vary according to the situation , Local time zone name with daylight saving time , And no .

The calendar (Calendar) modular

The functions of this module are calendar related , For example, print the character calendar of a month .

Monday is the first day of the week by default , Sunday is the last day by default . To change the settings, call calendar.setfirstweekday() function . The module contains the following built-in functions :

Serial number Functions and descriptions 1calendar.calendar(year,w=2,l=1,c=6) Returns the year Annual calendar ,3 Month and row , The interval is c. The daily width interval is w character . The length of each line is 21* W+18+2* C.l Is the number of lines per week .2calendar.firstweekday( ) Returns the setting of the start date of the current week . By default , First load calendar Module returns 0, Monday .3calendar.isleap(year) It's leap year back True, Otherwise False.>>> import calendar >>> print(calendar.isleap(2000)) True >>> print(calendar.isleap(1900)) False4calendar.leapdays(y1,y2) Back in the Y1,Y2 The total number of leap years between two years .5calendar.month(year,month,w=2,l=1) Returns the year year month Monthly calendar , Two line headings , A Monday trip . The daily width interval is w character . The length of each line is 7* w+6.l Is the number of lines per week .6calendar.monthcalendar(year,month) Returns a single nested list of integers . Each sublist load represents an integer for a week .Year year month All dates outside the month are set to 0; The days in the range are indicated by the day of the month , from 1 Start .7calendar.monthrange(year,month) Returns two integers . The first is the date code of the day of the week of the month , The second is the date code of the month . Day from 0( Monday ) To 6( Sunday ); Month from 1 To 12.8calendar.prcal(year,w=2,l=1,c=6) amount to print calendar.calendar(year,w=2,l=1,c=6).9calendar.prmonth(year,month,w=2,l=1) amount to print calendar.month(year,month,w=2,l=1) .10calendar.setfirstweekday(weekday) Set the start date code of the week .0( Monday ) To 6( Sunday ).11calendar.timegm(tupletime) and time.gmtime contrary : Accept a time tuple form , Returns the timestamp of the time (1970 Floating point seconds after the era ).12calendar.weekday(year,month,day) Returns the date code of a given date .0( Monday ) To 6( Sunday ). Month is 1( January ) To 12(12 month ).

Other related modules and functions

stay Python in , Other modules that deal with date and time are :

  • datetime modular
  • pytz modular
  • dateutil modular

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