cover Python Basic grammar , Master basic programming skills
Python It's a kind of object-oriented Of Interpretive computer programming language , By Guido . Van Rossum developed , The first public release was released on 1991 year , It is often called Glue language , Be able to make various modules in other languages ( In especial C/C++), Constant easy connection .
Python advantage
Python Open source , Developers are free to download , read , Even modify Python Source code
Python It has its own rich and Powerful library , And because of Python Of Open source , There are also many third-party libraries , for example : stay web Development has django.flask,Tornado, Reptiles scrapy, Scientific Computing numpy.pandas wait
because Python It's open source. , It has been ported to most platforms , for example :Windows,MacOS,Linux,Andorid,iOS wait
Python Both Support process oriented , It also supports object-oriented , This makes programming more flexible
Python shortcoming
C The program is very slow , because Python It's interpreted language , The code is translated line by line into CPU Machine code that can be understood , This translation process is very time-consuming , So it's slow , and C The program is compiled directly into CPU Executable machine code , therefore relative Python for ,C The language executes very fast
To publish the program you wrote , In fact, the source code is released , It is Interpretive language , The source code must be released
Python There are very Strict indentation Syntax , As long as the indentation error, the program crashes immediately
At any moment , Only one thread runs in the interpreter , Yes Python Access to the virtual machine is locked by the global interpreter (GIL) To control , Formally, this lock can ensure that only one thread is running at the same time , encounter i/o When blocked, it will release (GIL) therefore Python Multithreading is not really multithreading , It is CPU Very fast execution , It doesn't make people feel GIL The existence of .(GIL) Will be in Python Advanced stage explanation
[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-2eiqPEK6-1657892353562)(1.png)]
To learn the Python Can do
Comments are when you write a program , The person who wrote the program gave a sentence 、 Procedures section 、 Functions, etc Explain or prompt
The function of annotation :
A comment can serve as a comment , This method function , What on earth is a variable , If there is no comment for a long time, even if you write your own code , Maybe I don't know what this code is for , Therefore, the function of comments is to facilitate you to view the written code , Others to receive your code can understand , Simply put, it will be to improve the readability of the program code , For future reference 、 modify
Python in Use... For single line comments # Number ,# To the right of the number is the content of the note ,Python The parser encountered # The number will be used as a comment , Will not parse # After the number
Multiline comment ‘’‘ Code … ‘’’
#x It's a variable , When x=2 The result is 6 x=10 The result is 30
x=2
y=x*3
print(y)
Naming rules :
Variables must be in letters (a-z A-Z) Underline (_) start , Other characters can be alphanumeric underscores , Variables are case sensitive ,Python Keywords cannot be used as variable names
_Name=' Zhang San '
name=' Lau Andy '
print(_Name,name)
Naming specification :
Set two variables a=7,y=3
Return to Boolean True False
a=1
b=2
c=3
d=5
print(a>b and d>c) # The result is false
print(a>b or d>c)# The result is true
print(not a>d) # The result is true
priority :()–>not–>and–>or
print(2>1 and 1<4 or 2<3 and 9>6 or 2<4 and 3<2) #True
a,b,c,d=23,10,18,3
a+=3
print(a)
Output % Place holder
name =' Zhang San '
classPro=' Peking University, '
age =22
print(' My name is %s: come from %s This year, %d Year old '%(name,classPro,age))
me =' my '
classP=' First grade of Tsinghua high school 3 class '
age1=7
print('%s The name is Xiao Ming , come from %s, I this year %d Year old '%(me,classP,age1))
print(' I can \n A new line ')
print('\n')
print('-------------test---------------')
print('\n')
ID=' The professor '
QQ=66666666
number=13467204515
address=' Baiyun District, Guangzhou '
print('========================================')
print(' full name :%s'%ID)
print('QQ: %d'%QQ)
print(' Phone number :%d'%number)
print(' The company address :%s'%address)
print('========================================')
print('\n')
Formatting output is another way
print('--------- Formatting output is another way .format------------')
print(' full name :{}'.format(ID))
print('QQ:{}'.format(QQ))
print(' Phone number :{}'.format(number))
print(' The company address :{}'.format(address))
Input input
Python Provided in the input Method to get keyboard input
input The keyboard input received is str type , If you receive a numeric type, you need to str Turn into int
name=input(' Please enter a name ')
age2=int(input(' Please enter age :'))
qq=input(' Please enter QQNumber:')
phone=input(' Please enter your mobile number :')
addr=input(' Please enter the address :')
print(' full name :%s Age is %d'%(name,age2))
print('QQ:{}'.format(qq))
print(' Phone number :{}'.format(phone))
print(' The company address :{}'.format(addr))
score = 80
if score<=60: # If the conditions are met, the print prompt will be output
print(' The results are not ideal , Continue refueling ')
pass # Empty statement
print(' End of statement ')
if score>60:
print(' Good results. ')
else:
print(" The result is not up to standard , Continue to work hard ")
grade=int(input(' Please enter the grade :'))
if grade>90:
print(' Your score is A etc. ')
pass
elif grade>=80:
print(' Your score is B etc. ')
pass
elif grade >=70:
print(' Your rating is C etc. ')
pass
elif grade >=60:
print(' Your rating is D etc. ')
pass
else:
print(' You bastard ')
print(' End of program running .........')
xuefen=int(input(' Please enter your credits '))
if xuefen >10:
grade = int(input(' Please enter your score '))
if grade>=80:
print(' You can be promoted ... Congratulations ')
pass
else:
print(' unfortunately , Your grades are not up to standard ....')
pass
pass
else:
print(' Your performance is too bad 0')
Grammatical features
# 1. There is an initial value
# 2. Conditional expression
# 3. Variable 【 Circulating body count variable 】 Self increasing and self decreasing , Otherwise, it will cause a dead cycle
tage=' I am a Chinese '# The string type itself is a collection of character types
for item in tage:
print(item)
pass
#range This function can generate a list of data sets
#range( Starting value : End value : step ) Step cannot be 0
sum=0
for data in range(1,101):# The data contains , The right side does not contain 1-100
sum+=data
pass
#print(data,end=' ')
print(sum)
print('sum=%d'%sum)
# print('sum={}'.format(sum))
#
for message in range(50,201):
if message%2==0:
print('%d It's even '%message)
pass
else:
print('{} Is odd '.format(message))
# break Represents the end of the interrupt , If the conditions are met, the cycle of this layer will be ended directly
# continue End this cycle , Continue with the next cycle , ( When continue When conditions are met , The remaining statements in this loop will not be executed , The following cycle continues )
# These two keywords can only be used in a loop
while: For unknown number of cycles 【 Used to judge 】
for : Suitable for a known number of cycles 【 Iteratable object traversal 】
99 The multiplication table is used for Realization
# multiplication table
for i in range(1,10):
for j in range(1,i+1):
print('%d*%d=%d'%(i,j,i*j),end=' ')
print()# Control line feed
print('--------------------------------------------------------')
print('\n')
Case study Input 1-100 Data between
# Input 1-100 Data between
index =1# Defining variables
while index<=100:
print(index)
index+=1
pass
Case guessing game
# Case guessing game
import random
count =1
while count<=10:
person =int(input(' Please punch :【0 stone 1 scissors 2 cloth 】\n'))
computer=random.randint(0,2)# Random number range
if person==0 and computer==1:
print(' you are awesome ')
pass
elif person==1 and computer==2:
print(' You're great ')
pass
elif person==2 and computer==0:
print(' you are awesome ')
pass
elif person==computer:
print(' Good ah , Even tied ')
pass
else:
print(' Did you lose ')
pass
count+=1
multiplication table
# Print the multiplication table
i=1
while i<=9:
j=1
while j<=i:
print('%d*%d=%2d'%(i,j,i*j),end=" ")
j+=1
pass
print()
i+=1
pass
right triangle
# right triangle
row=9
while row>=1:
j=1
while j<=row:
print('*',end=' ')
j+=1
pass
print()
row-=1
pass
an isosceles triangle
# an isosceles triangle
i=1
while i<=10:
j1=1
while j1<=10-i:# Control the number of blank spaces in printing
print(' ',end='')
j1+=1
pass
k=1
while k<=2*i-1:# Control printing * Number
print('*',end='')
k+=1
print()
i+=1
pass
Guess age games
There are three requirements :
1. Allow users to try up to 3 Time
2. Every attempt 3 Next time , If you haven't guessed right , Just ask the user if he still wants to play , If the answer is Y or y, Just keep guessing 3 Time , In this way , If the answer is N or n, Just quit the program
3. If you're right , immediate withdrawal
# # import random
#
# # for i in range(3):
# # computer = random.randint(20, 22)
# # person = int(input(' Please enter age :'))
# # if person == computer:
# # print(' Congratulations on your correct answer ')
# # break
# #
# # else:
# # print(' Wrong guess. ')
# # zimu=input(' Whether or not to continue : Please input if you want to continue Y perhaps y Please input N or n')
# # if zimu=='Y' or zimu =='y':
# # pass
# # elif zimu=='N' or zimu=='n':
# # exit()
time =0
count=3
while time<=3:
age =int(input(' Please enter the age you want to guess :'))
if age ==25:
print(' You're right :')
break
elif age >25:
print(' You guessed it ')# else:
print(' Guess it's small ')
time+=1
if time==3:
choose=input(' Do you want to continue ?Y/N')
if choose == 'Y' or choose=='y':
time=0# Reset to initial value
elif choose=='N' or choose=='n':
exit()
else:
print(' Please enter the correct symbol .. Thank you for your cooperation ')
Xiao Wang's height 1.75, weight 80.5kg, Please according to BMI The formula ,【 Weight divided by the square of height 】, Help Xiao Wang calculate his BMI Index , And according to BMI Index
lower than 18.5 Over light
18.5-25 normal
25-28 overweight
28-32 obesity
higher than 32 Severe obesity
use if-elif Judge and print out
high=1.75
weight=80.5
BMI=weight/(high*high)
print('BMI The data of {}'.format(BMI))
if BMI<18.5:
print(' Over light ')
elif 18.5<=BMI<25:
print(' normal ')
elif 25<=BMI<28:
print(' overweight ')
elif 28<=BMI<32:
print(' obesity ')
else:
print(' Severe obesity ')
## Python data type
> master Python Basic data types for
* Numbers
* int( Signed integers )
* long( long integer )(Python3 Version cancelled )
* float( floating-point )
* complex( The plural )
* bool( Boolean value )
* return True False
* character string
* Dictionaries
* Tuples
* list
```python
a=[]
print(type(a)) #type Method to view the type of the variable
b=10
print(type(b))
Sequence : A set of values arranged in order ,【 Data set 】
Python in 3 The built-in sequence type in :
‘’’
character string list Tuples
‘’’
Sequence advantages : Supports indexing and slicing operations
features : The first positive index is 0, It points to the left end , The first index is negative , It points to the right end
Slicing refers to intercepting a certain section of a string ,
Slicing uses Syntax :[ Start subscript : End subscript : step ] The content intercepted by the slice does not contain the data corresponding to the end subscript , Step size refers to getting a character every few subscripts
The subscript will cross the line , Slice won't :
Test='python'
print(type(Test))
print(Test[0])# Get the first character
print(' Get the second character %s'%Test[1])
for i in Test:
print(i,end=' ')
name='peter'
print(' title case :%s'%name.capitalize())
a=' python '
print(a.strip())# Remove the spaces on both sides
print(a.lstrip())# Remove the space on the left
print(a.rstrip())# Remove the space on the right
# Assignment string
b=a
print(b)
print(id(a))# Check the memory address
print(id(b))
str="I Love Python"
print(str.find('P'))# Return the corresponding subscript Find the corresponding position of the target object in the sequence No return found -1
print(str.index('v'))#index() Check if there is a substring in the string , Return the corresponding subscript , If you don't find it, report it wrong
print(str.startswith('I'))# Return to Boolean Decide whether to start with something
print(str.endswith('i'))# Judge whether it ends with something
print(str.lower())# All lowercase
print(str.upper())# Capitalize all
st='hello world'
print(st[0])
print(str[::-1])# Output in reverse order
print(st[2:5])# From the subscript 2 The beginning does not contain 5【 Left closed right away 】
print(st[2:])# From the third character to the last
print(st[0:3])# from 0 At the beginning, you can omit 0
print(st[:3])
list=[]# An empty list
print(list)
print(len(list))# Get list object Number of data in
str='lodsa'
print(len(str))
listA=['abcd',123,456,798,True,12.255]
print(listA)
print(listA[0])# Find the first element
print(listA[1:3])
print(listA[3:])
print(listA[::-1])# flashback
print(listA*3)# Output data in the list many times 【 Copy many times 】
print('------------------ increase ---------------------')
listA.append('Jay')
listA.append([1,1,2,'dfgs',{
"al":12}])
print(listA)
listA.insert(1,' The elements inserted ')# The insert , You need to specify the insertion position
# reData=list(range(10))# Coercive transformation list object
listA.extend([12,45,484])# Expand , Batch addition
print(listA)
print('----------------- modify --------------')
print(' Before the change ',listA)
listA[0]='Peter'
print(' After the modification ',listA)
print('---------------------- Delete ---------------')
del listA[0] # Delete the first element in the list
print(listA)
del listA[1:3]# Batch deletion
print(listA)
listA.remove(798)# Indicate the specified element
print(listA)
listA.pop(0)# Remove the first element # Remove by subscript
print(listA)
Tuples are immutable sequences , You cannot make any changes after creation
variable
use () To create tuple types , Data items are separated by commas
It can be of any kind
When there is only one element in a tuple , Add a comma , Otherwise, the interpreter will be treated as plastic
Slicing is also supported
lookup
tupleA=()# An empty list
tupleA=('abcd',123,12.55,[123,45,'45hf'])
print(tupleA)
print(tupleA[2])
print(tupleA[1:3])
print(tupleA[::-1])
print(tupleA[::-2])
print(tupleA[-2:-1:])# Take the subscript upside down , -2 To -1 Interval data
print(tupleA[-4:-1])
tupleA[3][0]=250# Modify the list type data in tuples
tupleB=tuple(range(10))
print(tupleB.count(9))
Dictionary is not a sequence type , There is no concept of subscript , Is an unordered set of key values , Is a built-in advanced data type
A dictionary can store any object
Dictionaries are created in the form of key value pairs {key:value} Wrap with braces
When there is an element in the dictionary , According to the key , value Each element of the dictionary is composed of 2 Part of it is made up of : key : value
A safe way to access values get() Method , When we are not sure whether a key exists in the dictionary and want to get its value , have access to get() Method , You can also set the default value
Add dictionary data
dictA={
"pro":" Art major ","school":' Shanghai Academy of drama '}
dictA['name']=' Li Yifeng '
dictA['age']=29
print(dictA)
print(len(dictA))
print(dictA['name'])# Get value by key
dictA['name']=' Jackie Chan '# Modify the value of the key
print(dictA)
print(dictA.keys())# Get all keys
print(dictA.values())# Get all values
print(dictA.items())# Get all the keys and values
for key,value in dictA.items():
# print(item)
print('%s value ==%s'%(key,value))
dictA.update({
'age':32})# to update Update when there is , Add... If it doesn't exist
dictA.update({
"height":1.78})# add to
print(dictA)
del dictA['name']
dictA.pop('age')
print(dictA)
#+ Merge
strA=' Life is too short '
strB=' I use Python'
print(strA+strB)
List_A=list(range(10))
list_B=list(range(10,21))
print(List_A+list_B)
# * Copy
print(strA*3,end=' ')
print(List_A*3)
# in Determines whether an object exists
print(' I ' in strA)
print(10 in list_B)
master Python Function basis , Lay a solid foundation for the development project
In the process of programming , A function code block appears many times , But in order to improve the efficiency of writing and reuse of code , So organize the code blocks with independent functions into a small module , This is the function
It's a series Python The combination of sentences , You can run one or more times in a program ,
Generally, it has independent functions
Maximize code reuse and minimize redundant code , The overall code structure is clear , Problem localization
Function definition
def Function name ():
The body of the function 【 A series of statements , Represents an independent function 】
Function call
Define before calling
Function name plus () You can call
Function documentation :
The first line of the function content can be carried out with a string Function description
Function definition
def pritInfo():
'''
This function is used to print small pieces of information
'''
# Function code block
print(' Xiao Zhang's height is %f'%1.73)
print(' Xiao Zhang's weight is %f'%130)
print(' Xiao Zhang's hobby is %s'%' Jay Chou ')
print(' Xiao Zhang's major is %s'%' Information security ')
pritInfo()
def pritInfo(name,height,weight,hobby,pro):
# Function code block
print('%s His height is %f'%(name,height))
print('%s My weight is %f'%(name,weight))
print('%s My hobby is %s'%(name,hobby))
print('%s My major is %s'%(name,pro))
pritInfo('peter',175,130,' Listen to the music ',' Desserts ')
pritInfo(' petty thief ',189,140,' Play the game ',' Software engineer ')
Required parameters , Default parameters 【 Default parameters 】, Optional parameters , Key parameters
Parameters : In fact, the function is to realize a specific function , Then, in order to get the data needed to realize the function
In order to get external data
def sum(a,b):# Formal parameters : Just a parameter in the sense of , When defining, it does not occupy the memory address
sum=a+b
print(sum)
Required parameters
When the function is called , The required parameter must be assigned
sum(20,15)#20,15 Is the actual parameter Actual parameters , Real parameters , Is the actual memory address
sum() You can't write it like that , Need to pass the cords
def sum(a=1,b=11):
print(a+b)
sum()
sum(10)# At call time , If not assigned , Just use the default value given when defining the function
Variable parameters ( When the number of parameters is uncertain , More flexible )
def getComputer(*args):
''' Calculate the cumulative sum '''
# print(args)
result=0
for item in args:
result+=item
print(result)
getComputer(1)
getComputer(1,2,3,4)
# def Func(**kwargs):
# print(kwargs)
# Func(name=' Zhao song ')
# def Infofunc(*args,**kwargs): # Optional parameters must precede keyword optional parameters
# print(args)
# print(kwargs)
# Infofunc(1,2)
# Infofunc(12,13,46,age=18)
def num(*args):
''' # Write function , receive N A digital , Find the sum of these numbers '''
result=0
for i in args:
result+=i
return result
a=num(1,2,2,2,2)
print(a)
def Func1(con):
''' Find the element corresponding to the odd digit of the incoming list or tuple , And return to a new list '''
listA=[]
index=1
for i in con:
if index%2==1:# Judge odd digits
listA.append(i)
index+=1
return listA
# e=Func1([1,2,45,1,1,'as',{1,25,',hs'}])
e=Func1(list(range(1,11)))
print(e)
def Func2(dic):
''' Check each of the incoming dictionaries value The length of , If it is greater than 2, So just keep the first two lengths , And return the new content to the caller ,PS: The data in the dictionary can only be strings or lists '''
result={
}
for key,value in dic.items():
if len(value)>2:
result[key]=value[:2]# Add new data to the dictionary
else:
result[key]=value
return result
# call
dicObj={
'name':' Zhang San ','hobby':[' Sing a song ',' dance ',' Programming '],'major':' Information security '}
print(Func2(dicObj))
# Return value
def Sum(a,b):
sum=a+b
return sum # Return the calculation result to
result=Sum(12,15)# Assign the returned value to other variables
print(result)
def calComputer(num):
''' Cumulative sum '''
listA=[]
result=0
i=1
while i<=num:
result+=i
i+=1
# listA.append(result)
listA.append(result)
return listA
message=calComputer(10)
print(type(message))
print(message)
def returnType():
''' Returns tuple type data '''
return 1,2,3
a =returnType()
print(type(a))
print(a)
def returnType1():
''' Return dictionary type '''
return {
"name":" Jackie Chan "}
b=returnType1()
print(type(b))
print(b)
def fun1():
print("------------------fun1start")
print("-------------------- Execute code omission ")
print("-------------------fun1end")
def fun2():
print('------------------fun2start')
# Call the first function
fun1()
print("---------------------fun2end")
fun2()
# The function classification : According to the function return value and function parameters
# There are parameters and no return values
# There are parameters and return values
# No parameter, no return value
# No parameter has a return value
# pro=' Information security '# Global variables
# name=' Chow yun-fat '
# def printInfo():
# name=' Lau Andy '# local variable
# print('{}'.format(name))
#
# def TestMethod():
# name='peter'# local variable
# print(name)
# printInfo()
# TestMethod()
#
#
# def message():
# print(pro)
#
# message()
#
pro='123'
def changGlobal():
global pro
pro='456'
print(pro)
changGlobal()
stay Python in , Value is transmitted by reference , It can be used id() Check whether the references of an object are the same .
id Is the identification of the memory address where the value is stored in memory .
Immutable type
a=1
def func(x):
print('x The address of {}'.format(id(x)))
x=12
print(' Modified x The address of :{}'.format(id(x)))
print('a The address of :{}'.format(id(a)))
func(a)
li=[]
def testRenc(parms):
print(id(parms))
li.append([1,2,3,54])
print(id(li))
testRenc(li)
print(' External variable object {}'.format(li))
lambda Parameters 1、 Parameters 2、 Parameters 3: expression
characteristic
shortcoming
# Anonymous functions
m=lambda x,y:x+y
# Call anonymous functions through variables
print(m(23,19))
M=lambda a,b,c:a*b*c
print(M(1,2,3))
age =15
print(' You can continue to join the army ,'if age>18 else' Keep going to school ')
C=lambda x,y:x if x>y else y
print(C(1,5))
re=(lambda x,y:x if x<y else y)(16,12)
print(re)
Rs=lambda x:(x**2)+890
print(Rs(10))
If a function does not call other functions internally , But call yourself , This function is a recursive function
recursive Call yourself
There must be a clear end condition
# Factorial / By recursion
def factorial(n):
''' Factorial '''
if n==1:
return 1
return n*factorial(n-1)
result =factorial(5)
print(result)
# Factorial through ordinary functions
def jiecheng(n):
''' Factorial '''
result=1
for item in range(1,n+1):
result*=item
return result
re=jiecheng(5)
print(re)
# Simulation Implementation , Traversal of tree structure
import os # Introduce file operation module
def findFile(file_Path):
listRs=os.listdir(file_Path)# Get the folder under the path
for fileItem in listRs:
full_Path=os.path.join(file_Path,fileItem)# Get the complete file path
if os.path.isdir(full_Path):# Determine whether it is a folder
findFile(full_Path)# If it's a file , Go over again
else:
print(fileItem)
else:
return
#d Call search file object
findFile('D:\\Python')
#Python Functions that come with language
print(abs(-23))# Take the absolute value
print(round(2.23))# Approximate value
print(round(12.56,1))# Keep one decimal place
print(pow(3,3))# Power
print(3**3)# Power
print(max(12,15,18))# Return maximum
print(min(12,15))# minimum value
print(sum(range(50)))
#eval Execute expression
a,b,c=1,2,3
print(' Dynamically generated functions {}'.format(eval('a+b+c')))
#chr() Number to character
#bin() Change to binary
#hex() To hexadecimal
#oct() To octal
#list() Convert tuples to list
print(bin(10))
print(hex(16))
tupleA=(132,2,2,23,1)
print(list(tupleA))
listA=[1,123,15,',ghdj']
print(tuple(listA))
# bytes transformation
print(bytes(' I like Python',encoding='utf-8'))
#sorted() Function to sort all objects that can be iterated Generate a new one to sort
#sort() Sort based on the original data
#all()
#range()
list=[1,2,3,45,6]
# list.sort()# Modify the original object directly
print('------------- Before sorting -----------{}'.format(list))
# varList=sorted(list)
varList=sorted(list,reverse=True)# null
# varList=sorted(list,reverse=False)# Ascending sort
print('------------- After the sorting -----------{}'.format(varList))
#set Index slicing is not supported , Is an unordered and non repeating container
# It's like a dictionary , But only Key, No, value
set1={
1,2,3}
set1.add(123)# Add operation
set1.clear() # Empty
print(set1)
List1=['1','2','24']
set2=set(List1)
print(set2)
re=set1.difference(set2)# Difference set , a In some b Not found in
print(re)
print(set1-set2)# Difference set
print(set1.intersection(set2))# intersection
print(set1&set2)# intersection
print(set1.union(set2)) # Combine
print(set1 | set2)# Combine
#pop Is to take data from the set and delete it at the same time
print(set1)
set1.pop()
print(set1)
set1.discard(3)# Specifies to remove the element
print(set1)
#update Two sets
set1.update((set2))
print(set1)
Introduce Python Object oriented development , Lay a solid foundation for the development project
object-oriented programming oop 【object oriented programming】 It's a kind of Python Programming ideas
Process oriented :
When thinking about problems , How to follow the steps to achieve ,
Then divide the problem solving into several steps , And these steps correspond to the final function of the method step by step
Process oriented : Is the beginning of learning , Follow the problem-solving steps to write code 【 Write code according to business logic 】
object-oriented : Focus on design thinking 【 Find a car wash , Pay for the car wash 】
From a computer perspective : Process oriented is not suitable for large projects
Process oriented focuses on : How do you do it?
Object oriented focuses on : Who will do it
class : It's a template , The template contains multiple functions , Functions to achieve some functions
object : Instance created from template , Function in class can be executed through instance object
Class by 3 Part of the form :
for example : Create a human being
The name of the thing ( Class name ): people (Person)
attribute : height , Age
Method ; eat run …
Real world Computer world
Behavior ------》 Method
features ------》 attribute
# Define classes and objects
# Class name : Name it in the way of big hump
# Create objects
# Object name = Class name ()
''' class Class name : attribute Method '''
# Example method :
# Inside the class , Use def Keyword can define an instance method , And general functions Different definitions , Class method must contain parameters self【self It can be other names , But this position must be occupied 】, And it's the first parameter
# attribute : In class Internally defined variables
# Defined in class , The attributes outside the method become class attributes , The definition is used in the method self The referenced properties are called instance properties
class Person:
''' The characteristics of the corresponding person '''
name=' Xiaoyong ' # Class properties
age=22 # Class properties
''' Corresponding person's behavior '''
def __int__(self):
self.name = ' Xiao zhao '# Instance attributes
def eat(self):# Example method
print(' Devour ')
def run(self):# Example method
print(' Run fast ')
# Create objects 【 Class instantiation 】
xm=Person()
xm.eat()# Call function
xm.run()
print('{} The age of {}'.format(xm.name,xm.age))
# If there is n Such an object Be instantiated , Then you need to add instance attributes many times , Obviously it's more troublesome
class Person1:
def __init__(self):# Magic methods
''' Declaration of instance properties '''
self.name=' Xiaoyong '
self.age=22
self.sex=' schoolboy '
def run(self):
print(' Running too fast ')
xy=Person1()
# xy.run()
print(xy.age)
class Person:
def __init__(self,pro):
self.pro=pro
def geteat(s,name,food):
# print(self)
print('self Address in memory %s'%(id(s)))
print('%s Like to eat %s, The major is :%s'%(name,food,s.pro))
zs=Person(' psychology ')
print('zs Memory address of %s'%(id(zs)))
zs.geteat(' Xiao Wang ',' durian ')
Magic methods : __ xxx __
''' __init__ Method : Initialize a class , Use... When creating an instance object and assigning values to it __str__ Method : When converting an object to a string str( object ) When it comes to testing , Print the information of the object __new__ Method : Create and return an instance object , Called once , You get an object __class__ Method : Get classes of known objects ( object __class__) __del__ Method : This method is called when the object is destroyed after the program runs , To release resources '''
class Animal:
def __init__(self,name,color):
self.name=name
self.color=color
print('--------init-------')
def __str__(self):
return ' My name is %s, My color is %s'%(self.name,self.color)
def __new__(cls, *args, **kwargs):
print('--------new-------')
return object.__new__(cls)
dog =Animal(' Wangcai ',' black ')
print(dog)
''' __new__ and __init__ Function difference __new__ Class instantiation method : The instance must be returned Otherwise, the object will not be created successfully __init__ Used to initialize data properties , It can also be considered as the construction method of the instance , Receive an instance of the class self And construct it __new__ At least one parameter is cls Represents the class to be instantiated , This parameter is instantiated by Python The interpreter operates automatically __new__ The function must be executed before __init__ function '''
''' When an object is deleted or destroyed ,python The interpreter will call a method by default , This method is __del__() Method , Also known as the destructional method '''
class Animals:
def __init__(self,name):
self.name=name
print(' This is the construction initialization method ')
def __del__(self):
print(' When under a scope , Without being quoted , The interpreter will automatically call this function , To free up memory space ')
print(' This is the deconstruction method ')
print('%s This object is completely cleaned up , Memory space has been freed '%self.name)
cat=Animals(' Cat and cat ')
# del cat # Manually clean up and delete objects
input(' Program waiting ......')
# When the whole program script is executed, it will automatically call _del_ Method
# It will also be called automatically when the object is destroyed manually _del_ Method
# Deconstruction methods are generally used for resource recovery , utilize _del_ Method to destroy an object and reclaim memory resources
Python Show three types of object-oriented : encapsulation , Inherit , many
state
encapsulation : It's worth encapsulating the content somewhere , It is convenient for later use
He needs to :
Encapsulate the content somewhere , Go from another place to call the encapsulated content
For encapsulation , In fact, it is to use the initialization construction method to encapsulate the content into the object , And then through the object directly or self To get the encapsulated content
Inherit : It's the same as inheritance in real life , That is, the son can inherit the content of the father 【 Attributes and behaviors 】( Some fathers have sons , contrary , Some sons have fathers, not necessarily ),
Polymorphism , The type of definition time is different from that of runtime , This is called polymorphism
class Animal:
def eat(self):
''' eat '''
print(' eat ')
def drink(self):
''' drink '''
print(' drink ')
class Dog(Animal):# Inherit Animal Parent class , here Dog It's a subclass
def wwj(self):
print(' bark ')
class Cat(Animal):
def mmj(self):
print(' mews ')
d1=Dog()
d1.eat()# Inherited the behavior of the parent class
d1.wwj()
c1=Cat()
c1.drink()
c1.eat()
''' For object-oriented inheritance , In fact, it is to extract the methods common to multiple subclasses into the parent class , Subclasses only need to inherit from the parent class without having to implement them one by one This can greatly improve efficiency , Reduce code duplication , Streamline the hierarchy of code To facilitate extension class Class name ( Parent class ): pass '''
class shenxian:
def fly(self):
print(' Gods can fly ')
class Monkey:
def chitao(self):
print(' Monkeys like to eat peaches ')
class SunWuKong(shenxian,Monkey):
pass
swk=SunWuKong()
swk.fly()
swk.chitao()
# When the same method exists in multiple parent classes ,
class D:
def eat(self):
print('D.eat')
class C(D):
def eat(self):
print('C.eat')
class B(D):
pass
class A(B,C):
pass
a=A()
# b=B()
a.eat()
print(A.__mro__)# You can inherit the relationship of real classes in turn Find the execution order
# In execution eaet When the method is used , The order should be
# First of all to A Go inside , If A There is no , Then go on B Class to find , If B There is no , Then go C Search for ,
# If C Not in class , Then go D Search in class , If you haven't found it yet , You're going to report a mistake
#A-B-C-D It's also the order of inheritance
class Father:
def smoke(self):
print(' Smoke the lotus King ')
def drink(self):
print(' Drink Erguotou ')
class Son(Father):
# With the father ( smoking ) The method has the same name , This is overriding the parent method
def smoke(self):
print(' Smoke Chinese ')
# After overriding the parent method , When a subclass calls a parent method , What will be called is the subclass method
son=Son()
son.smoke()
# To achieve polymorphism , There must be two premises to be observed :
''' 1. Inherit : Polymorphism must be released between parent and child classes 2. rewrite : Subclasses override methods of the parent class '''
class Animal:
''' Base class [ Parent class ] '''
def say(self):
print(' I'm an animal '*10)
class Dark(Animal):
''' Subclass 【 Derived class 】 '''
def say(self):
''' Override parent method '''
print(' I am a duck '*10)
class Dog(Animal):
def say(self):
print(' I am a '*10)
# dark=Dark()
# dark.say()
# Call uniformly
def commonInvoke(obj):
obj.say()
list=[Dark(),Dog()]
for item in list:
''' Loop function '''
commonInvoke(item)
Class properties : Is the attribute owned by the class object , It is shared by instance objects of all class objects , Class objects and instance objects can access
Instance attributes : Properties owned by the instance object , Can only be accessed through instance objects
class Student:
name =' The dawn '# Belongs to class attribute , Namely Student Class objects have
def __init__(self,age):
self.age=age # Instance attributes
lm=Student(18)
print(lm.name)
print(lm.age)
print(Student.name)# adopt Student Class object access name attribute
# print(Student.age)# Class objects cannot access instance properties
# Class objects can be accessed and used by class objects and instance objects
# Instance objects can only be accessed by instance objects
class People:
country='china'
@classmethod # Class method use classmethod To embellish
def get_country(cls):
return cls.country# Access class properties
@classmethod
def change_country(cls,data):
cls.country=data# Modify the value of column attribute , In the class method
@staticmethod
def gatData():
return People.country
@staticmethod
def add(x,y):
return x+y
print(People.gatData())
p=People()
print(p.gatData())# Be careful : In general , We will not access static methods through instance objects
print(People.add(1,2))
# print(People.get_country())# Refer to... Through class objects
# p=People()
# print(' Access through instance objects ',p.get_country())
# People.change_country(' The British ')
# print(People.get_country())
# Because static methods are mainly used to store logical code , It does not interact with classes and instance objects
# in other words , In a static method , It will not involve the operation of methods and properties in the class
# Data resources can be effectively and fully utilized
import time
class TimeTest:
def __init__(self,hour,minute,second):
self.hour=hour
self.minute=minute
self.second=second
@staticmethod
def showTime():
return time.strftime('%H:%M:%S',time.localtime())
print(TimeTest.showTime())
# t=TimeTest(2,10,11)
# print(t.showTime())# There is no need to access static methods through instance objects
grammar :
Scenarios using privatized attributes
To access private variables, you usually write two methods , A visit , A modification , Access is controlled by methods
class Person:
__age =18 # Instance a privatized attribute , Attribute names are preceded by two underscores
‘’’
class Person:
__hobby = 'dance'
def __init__(self):
self.__name = ' Li Si ' # Add two underscores to privatize this property , No more direct external access , It can be accessed inside the class
self.age = 30
def __str__(self):
return '{} The age of {}, like {}'.format(self.__name, self.age, Person.__hobby) # Call the privatization property
def change(self, hobby):
Person.__hobby = hobby
class Studeng(Person):
def printInfo(self):
# print(self.__name)# Cannot access private properties in the parent class
print(self.age)
pass
xl = Person()
# print(xl.name)# By class object , Externally accessible
print(xl)
xl.change(' Sing a song ') # Change the value of the private property
print(xl)
stu = Studeng()
stu.printInfo()
stu.change('Rap')
print(stu)
# print(xl.hobby) # Access class properties through instance objects
# print(stu.hobby) # Access class properties through instance objects
# print(Person.hobby) # Access class properties through class objects
‘’’
_xxx Underline before , Beginning with a single underscore indicates protected Variable of type , That is, the protection type can only be accessed by itself and its subclass , Out of commission from xxx import * How to import
__xxx__ Two underscores before and after , Magic methods , It's usually python Self contained , Developers should not create this type of method
xxx_ Single underline on the back , Avoid attribute names and Python Keyword conflict
class A:
def __myname(self): # Precede the method name with two underscores
print(‘ Xiao Ming ’)
class Animal:
def __eat(self):
print(' Eat something ')
def run(self):
self.__eat() # Call the privatization method here
print(' Run fast ')
class Bird(Animal):
pass
bird = Bird()
bird.run()
# Property function (property)
class Perons:
def __init__(self):
self.__age = 18
def ger_age(self):# Access private instance properties
return self.__age
def set_age(self, age):# Modify private instance properties
if age < 0:
print(' Too young ')
else:
self.__age = age
# Define a class property , The implementation accesses private properties in the form of direct access to properties
age=property(ger_age,set_age)
p=Perons()
print(p.age)
p.age=-1
print(p.age)
Learn to use Python Operation file , understand Python Garbage collection mechanism
Write data in binary form
''' fobj=open("./Test1.text","wb")# str--->bytes fobj.write(" Between the dark clouds and the sea ".encode("utf-8")) fobj.close() '''
The binary form is appended
''' # Additional not required encode() #fobj=open("Test.text","a")# Additional data #fobj.write(" Between the dark clouds and the sea \r\n") #fobj.write(" Petrels are like black lightning \r\n") fobj=open("./Test1.text","ab")# str--->bytes fobj.write(" Today, poetry is booming \n".encode("utf-8")) fobj.close() '''
Read file data
#fobj=open('./Test.text','r')
fobj=open('./Test.text','rb')
data=fobj.read()
print(data)
print(data.decode("utf-8"))# Read all data
#print(fobj.read(12))# Read two data
#print(fobj.readline())# Read a row of data
#print(fobj.readlines())# Read all lines , Returns a list of
fobj.close()# The file object is closed
with open("withfile.text",'r') as f:
#f.write("123 Wooden man ")
print(f.read())
Learn regular expression operation string
re The module is to use C The language doesn't match, and the speed is very fast
among compile Function to generate a regular expression object based on a pattern string and optional flag parameters , This object has a series of methods for regular table assembly matching and replacement ,re The module also provides functions that are completely consistent with the functions of this method , These functions apply a pattern string as their first argument
re.macth Method
import re
str='Python is the best language in the world'
result= re.match('P',str)
print(type(result))#<class 're.Match'>
print(result.group())
Sign a
import re
strData='Python is the best language in the world\
gslfjgldsjgls'
#result= re.match('p',strData,re.I|re.M)# The third parameter Ignore case
#print(type(result))#<class 're.Match'>
#print(result.group())
res=re.match('(.*?)is(.*?)',strData,re.I)
print(res.group(1))
print(res.group(2))
Common matching rules
Number of matching characters
import re
# * Match previous character appears 0 Times or infinite times
res=re.match('[a-z][a-z]*','MyPython',re.I)
print(res.group())
# + Match the previous character 1 Times or infinite times At least once
res=re.match('[a-zA-Z]+[\w]*','mynAMEDCeisz848s_')
print(res.group())
# ? Match the previous character 0 Time or 1 Time
res=re.match('[a-zA-Z]+[\d]?','mkohjhjgu8jg8')
print(res.group())
# {min,max} Match the previous from min To max Time min max Must be a non negative integer
#{count} The exact number of matches {count,} There is no limit to
res=re.match('\d{4,}','46145')
if res:
print(' The match is successful {}'.format(res.group()))
# Match mailbox Format :[email protected]
res=re.match('[a-zA-Z0-9]{6,11}@163.com','[email protected]')
print(res.group())
# path="D:\\1_zhao_File\\1_MarkDown\MarkDown Learn to use "
# print(path )
import re
# Native string r
print(re.match(r'c:\\a.text','c:\\a.text').group())
# Match the beginning and the end
#^ Match the beginning of a string
#$ Match string end
# res=re.match('^p.*','python is language')
res=re.match('^p[\w]{5}','python is language')
print(res.group())
res=re.match('[\w]{5,15}@[\w]{2,5}.com$','[email protected]')
print(res.group())
# | Match any expression left or right From left to right
import re
res=re.match('[\w]*|100','100')
print(res.group())
# (ab) Packet matching Use the characters in brackets as a group
res=re.match('([0-9]*)-(\d*)','123456-464651561')
print(res.group())
print(res.group(1))
print(res.group(2))
# \num Use
# htmlTag='<html><h1>Python Programming core </h1></html>'
# res1=re.match(r'<(.+)>(.+)>(.+)</\2></\1>',htmlTag)
# print(res1.group(1))
# grouping The use of aliases (?P< name >)
data='<div><h1>www.baidu.com</h1></div>'
res=re.match(r'<(?P<div>\w*)><(?P<h1>\w*)>(?P<data>.*)</\w*></\w*>',data)
print(res.group())
# re.compile Method
''' compile Compile the regular expression pattern into a regular expression object reg=re.compile(pattern) result=reg.match(string) Equivalent to result=re.match(pattern,string) Use re.compile And keep the resulting regular expression object reuse efficiency higher '''
import re
#compile You can compile strings into bytecodes
# advantage : When using regular expressions match when ,python Will convert the string to a regular expression object
# And if you use compile, You only need to convert once , There is no need to repeat the conversion when using schema objects in the future
data='1364'
pattern=re.compile('.*')
# Use pattern object
res=pattern.match(data)
print(res.group())
#re.search Method
#search Match once in the full text , Match to return
data=' I love my great motherland ,I love China,China is a great country'
rees=re.search('China',data)
print(rees)
print(rees.span())
print(rees.group())
# print(data[21])
#re.findall Method Match all , Return a list ,
data=' Huawei is the pride of Chinese '
# res =re.findall(' Hua .',data)
# print(res)
pattern=re.compile(' Hua .')
res=pattern.findall(data)
print(res)
# re.sub Method Realize target search and replacement
data1='Pythons Is a very popular programming language '
pattern='[a-zA-Z]+' # Character set range + representative Leading character mode appears 1 From above
res=re.sub(pattern,'C#',data1)
resn=re.subn(pattern,'C#',data1)
print(res)
print(resn)
#re.subn Complete the search and replacement of goals It also returns the quantity replaced , Returns... As a tuple
#re.split Is the new split string
data=' Baidu , tencent , Ali , Huawei ,360, Bytes to beat '
print(re.split(',',data))
''' python The default is greedy , Always greedily match as many characters as possible , Not greedy, on the contrary , Always try to match as few characters as possible stay ” * ? + {m,n}" Followed by ? To turn greed into non greed '''
# greedy
import re
res=re.match('[\d]{6,9}','111222333')
print(res.group())
# Not greed
res=re.match('[\d]{6,9}?','111222333')
print(res.group())
content='asdfbsdbdsabsd'
# pattern=re.compile('a.*b')# greedy
pattern=re.compile('a.*?b')# Not greed
res=pattern.search(content)
print(res.group())
#0710-49