1python The creator of this is “ Uncle GUI ”Guido van Rossum
2python The shortcomings of language
Slow running speed python It's interpreted language ( It is different from the compiled type ), The code needs to be translated into CPU Machine code that can be understood . however , Does not affect user interaction , Because, for example python need 0.1,C need 0.001s, And the network needs 1s,1.1s and 1.001s There's no difference Code cannot be encrypted python Only source code can be published , and C Languages can only be published .exe file3 Interpreter
CPython The official interpreter . Yes, it is C Language development . Run on the command linepython
That is to start. CPython Interpreter .IPython stay CPython Developed on the basis of , Only in terms of interactivity PyPy use JIT technology , Yes python Make dynamic compile , The main purpose is to improve the execution speed Jython Can be in Java On the platform Python Interpreter , You can directly Python Code compiled into Java Bytecode execution IronPythonAt Microsoft .Net On the platform Python Interpreter , You can directly Python Code compiled into .Net Bytecode
4 Command line mode and interactive mode
Command mode Open it directly cmd. The effect is C:\> _ Interactive mode stay cmd Input in python. The effect is >>> _5 How to execute python file ?
In command mode, in hello.py Catalog learn Execute the following statement under . Input code directly to execute in interactive mode
C:\learn> python hello.py
6python Common libraries and usage
Scientific Computing Numpy,Scipy Data analysis Pandas drawing matplotlib data mining scikit-learn,nltk,pytorch/tensorflow( Deep learning ) game Pygame/Bigworld Images PIL Robot control PyRO1 Input and output
Output :print()
print('hello,world')
print('The quick brown fox', 'jumps over', 'the lazy dog')
Be careful , If we use the second way ,print()
Each string will be printed in turn , Comma encountered “,” Will output a space
Input :input()
# Be careful , Is string input
name = input()
# It can be prompted input
name = input('please enter your name: ')
print('hello,', name)
# Enter two integers
a,b=map(int,input().split())
# Enter two strings
a,b=input().split()
2 data type
data type Be careful Integers1 Hexadecimal such as oxff01
2_ Use :100000000=100_000000, This is because it is convenient to see 0 The number of
3 No size limit
4 3**5=243, Express 3^5
Floating point numbers1 Such as 1.23e8
2 No size limit , Out of range is inf( infinity )
character string1" " And ' ': Both can be used , But if there is... In the string ' When , Need to use " " Such as "I‘m OK’"
2 stay 1 You can also use escape characters to solve the problem , Such as 'I\'m OK'
3 If there are many characters in the string that need to be escaped , But I want to '' Parts of the are not allowed to be escaped , have access to r'' Here's the picture
4 If there are many line breaks in a line, it is inconvenient to use , have access to '''...''' Here's the picture
5 immutable Orderly
Boolean value1True and False
2 Arithmetic :and or not
Null value Nonelist ,
Dictionaries ,
Custom data types
list Variable order s = ['python', 'java', ['asp', 'php'], 'scheme']
tuple Immutable order t = (1, 2)
dict Variable disorder d={'Anne':96,'Bob':84,'Candy':87}
set Variable or immutable can be disordered s = set([1, 1, 2, 2, 3, 3])
Variable1 Variable names can be case 、 Numbers and _ , Cannot start with a number
2 The type of a variable can be assigned repeatedly , And different data types . such A language in which the type of the variable itself is not fixed is called Dynamic language
3 a=‘ABC’, Memory does two things , To create a ‘ABC’ String and create a a The variable of , And will a Point to 'ABC'
Constant1 Python There are no complete constants in , It is usually expressed in uppercase characters
Global variables 1 global Global variablessummary : String and meta combinations are immutable , character string 、 Tuples 、 The list is ordered
print('\\\t\\')
print(r'\\\t\\')
print('''line1
line2
line3''')
3 Operation symbol
/ The result must be a floating-point number // The result must be an integer , Rounding down % The result must be an integerConclusion :// and % The result must be an integer , So the result must be accurate
priority
4 Character encoding
ASCII1 Bytes , Only a few commonly used symbols Unicode2~6 Bytes , And ASCII The connection is , Used to represent ASCII There are two bytes , The first byte is all 0, The main functions are Show Show the user UTF-8 A combination of ASCII and Unicode Byte length of , More flexible , For example, English is 1 Bytes , Chinese characters are 3 Bytes , To save space , The main functions are preservation11100100 10111000 10101101
Memory :Unicode
External storage / Browser source code / To transmit data :UTF-8
5 character string
Use Unicode Encoding
ord() The character is converted to Unicode code , Such as ord(‘A’)chr()Unicode Convert code to character , Such as chr(''66)int() Character numbers are converted to numeric values encode() Characters are converted to the specified encoding bytes type , Such as 'ABC'.encode('ascii'),' chinese ’.encode('utf-8')decode() Characters are converted to the specified encoding str type , Such as b'ABC'.decode('ascii',errors='ignore')#ignore A small number of invalid characters are ignored , Of course, you can not add itlen()
bytes Type count bytes ,str Type count characters String name [::-1] In reverse order .islower() Judge whether it's all lowercase Convert to lowercase s.lower() Convert to uppercase s.upper() First word capitalization s.title() The first string letter is capitalizeds.capitalize()
>>> len(' chinese ')
2
>>> len(' chinese '.encode('utf-8'))
6
>>> len('ABC')
3
>>> len(b'ABC')
3
# toggle case
w = "100hello WORLD"
w.upper()
Out[72]: '100HELLO WORLD'
w.lower()
Out[73]: '100hello world'
w.title()
Out[74]: '100Hello World'
w.capitalize()
Out[75]: '100hello world'
Be careful : We read the byte stream from the network or disk , It's used bytes, Because we often encounter when we operate on strings str and bytes The mutual transformation of , In order to avoid confusion , We should insist on using UTF-8 To transform , Namely encode and decode The following parameter is utf-8.
str Is immutable
>>> a = 'abc'
>>> a.replace('a', 'A')
'Abc'
# The above actually creates a new object
>>> a
'abc'
explain : For immutable objects , Call any method of the object itself , It doesn't change the content of the object itself . contrary , These methods create new objects and return , such , It ensures that the immutable object itself is immutable .
python The invariant objects in are :str None
Fetch substrings between specific characters
# Here is to take out [ ] String between
m=re.findall(r"\[(.+?)\]",L)
6 format
and c The output of the language is the same
%x Hexadecimal integer
print('%s has %d dollars'%('Tom',100))
print('%s'%(3))# there 3 Is there any ' It's all right , because s Can automatically convert integers to strings
# Specify the number of output bits and whether the output bits need to be preceded by 0
print('%2d-%02d' % (3, 1))
# Number of decimal points output
print('%.2f' % 3.1415926)
# Output band % When
print('%d %%' % (7))
#format()
>>> 'Hello, {0}, The results have improved {1:.1f}%'.format(' Xiao Ming ', 17.125)
'Hello, Xiao Ming , The results have improved 17.1%'
#f-string
>>> r = 2.5
>>> s = 3.14 * r ** 2
>>> print(f'The area of a circle with radius {r} is {s:.2f}')
The area of a circle with radius 2.5 is 19.62
7 Special data types list
list : A collection
The element data types inside can be different , And you can set a doll , for example
s = ['python', 'java', ['asp', 'php'], 'scheme']
# That is to say
p = ['asp', 'php']
s = ['python', 'java', p, 'scheme']
len() Such as len(classmates)a[-1]
a[-2]
Get the last first element
~ Two ~
insert() Insert the specified position, such as a.insert(1,'jack'), Insert into Subscript by 1 The location of append() Follow up at the end and add new elements a.append('Anne')extend() Add a list of elements at the end, such as a.extend(['Anne','Bob'])pop()Delete trailing elements such as a.pop()
Delete the element at the specified position, such as a.pop(4)
a[2]='dudu'Replace the element at the specified location
sort()Positive sequence sort , Such as a.sort()
Use lamda Custom sort , Such as l.sort(key=lambda x:x[1])
reverse() Reverse sort , Such as a.reverse()index()Get the subscript of an element, such as l.index('Anne')
count() The number of times an element appears, such as l.count('Anne') List additionMerge and add
[1,2,3]+[5,3] >>> [1,2,3,5,3]
The list of multiplicationRepeat... Several times
[1,2,3]*2 >>> [1,2,3,1,2,3]
Realize two-dimensional array
l1=[]
i=0
while i<5:
l1.append([])
i+=1
l1.append(' Hello ')
And random Libraries are used in combination
L=[3,4,1,3,4,5,1]
# Randomly select an object from the list
random.choice(L)
# The list is messed up
random.shuffle(L)
8 Special data types tuple
The difference in list: Cannot be modified after initialization
# When there are no elements
t = ()
#1 Elements
t = (1,)
#2 Element time
t = (1, 2)
Be careful : If it is 1 Elements ,t=(1) It's wrong. , Because it can express tuple It can also express the parentheses of mathematical calculation ,python The default is the latter , Therefore, the above formula is equivalent to t=1
Immutability means that the object is immutable , The contents of the object may change , That's it list, as follows
>>> t = ('a', 'b', ['A', 'B'])
>>> t[2][0] = 'X'
>>> t[2][1] = 'Y'
>>> t
('a', 'b', ['X', 'Y'])
9 Special data types set
And list comparison , But it can't be repeated internally
It is generally used as a weight removal tool
>>> s = set([1, 1, 2, 2, 3, 3])
>>> s
{1, 2, 3} #print As a result {}
increase s.add(5) Delete s.remove(4) and / hand over & |10 Special data types dict
Dictionaries : storage : key - value , Easy and fast search . It is very similar to a two-dimensional array or pointer array
d={'Anne':96,'Bob':84,'Candy':87}
print(d['Anne'])
Judge whether the key exists 1 Mode one :in
if 'Bob' in d:
print(d['Bob'])
Mode two :get()
if d.get('Bob'):
print(d['Bob'])
2 Custom return value
print(d.get('Bobc','sorry'))increase
1 direct d['Duduo']=88
Delete d.pop('Bob') a d['Anne']difference : And list comparison , It is fast to find and insert , It doesn't slow down with the increase of elements , But it takes a lot of memory
11 Conditional control statements
age = 20
if age >= 18:
print('adult')
elif age >= 6:
print('teenager')
else:
print('kid')
if < conditional 1>:
< perform 1>
elif < conditional 2>:
< perform 2>
elif < conditional 3>:
< perform 3>
else:
< perform 4>
Be careful :python Judge from top to bottom , Once a judgment is True, The following will not be executed , For example, the above result is adult
Abbreviation form , Be similar to switch
if x:
print('True')
12 loop
for...in loop : Generally used for traversal
names = ['Michael', 'Bob', 'Tracy']
for name in names:
print(name)
Calculation 1+2+3+...+100
#range(n) It's automatic generation 0~n Integer sequence of
#range(101) It's from 0 To 100, in total 101 A digital
sum = 0
for x in range(101):
sum = sum + x
print(sum)
# coordination list Use
ls1=[i for i in range(1,101)]
print(sum(ls1))
# Output 0~100 The integer of
print(list(range(101)))
while loop
sum=0
n=100
while n>0:
sum+=n
n-=1
print(sum)
Of course ,break and continue The same applies
13 Data type conversion
Basic data type conversion
>>> int('123')
123
>>> int(12.34)
12
>>> float('12.34')
12.34
>>> str(1.23)
'1.23'
>>> str(100)
'100'
>>> bool(1)
True
>>> bool('')
False
str list dict Type conversion
#list-->str
s = ''.join(l)
#list-->dict
l1 = ['a', 'b', 'c']
l2 = [1, 2, 3]
dict(zip(l1,l2))
#str-->list
l=s.split(',') Suitable for all commas or spaces
perhaps
l=list(s)
#str-->dict
s = '{"id": 1, "name": "li"}'
d = eval(s)
#dict-->list
d = {'a': 1, 'b': 2, 'c': 3}
list(d)
## ['a', 'b', 'c']
list(d.keys())
## ['a', 'b', 'c']
list(d.values())
## [1, 2, 3]
#dict-->str
str(d)
Pay special attention to list-->dict When
zip The underlying principle is Traversal assignment , If l1 If there are duplicate fields, assign them to l2 Last value
l1 = ['a', 'b', 'a']
l2 = [1, 2, 3]
dict(zip(l1,l2))
## {'a': 3, 'b': 2}
dict(zip(l2,l1))
## {1: 'a', 2: 'b', 3: 'a'}
Common handling of strings
#str Remove the symbol from the beginning and end of the type
str2.strip( ',' )
1 Assign a function name to a variable
>>> a = abs # Variable a Point to abs function
>>> a(-1) # So you can also pass a call abs function
1
2 Custom function
Format def Function name ( Parameters ):
The body of the function
def my_abs(x):
if x >= 0:
return x
else:
return -x
# Using ternary expressions
def my_abs(x):
return x if x>=0 eles -x
Be careful : If not return, In fact, there will be return Of , That is to say None
3 Empty function
pass: Don't do anything? , I haven't figured out how to write it yet , But let the program run first
def nop():
pass
if age >= 18:
pass
4 Return multiple values
def hello(x,y):
return x,y
print(hello(1,2))
# The result is (1,2)
a,b=hello(1,2)
# Get the return value
By the result (1,2) You can know that the actual return is tuple
5 Functions with default arguments
background : If I want to use different arguments to the same function , The system will report an error and say that the parameters are incorrect .
practice : Set the default parameter default , The required parameters are in front , The parameters with large changes are later , For example, next
def power(x, n=2):
s = 1
while n > 0:
n = n - 1
s = s * x
return s
therefore power(5) Equivalent to power(5,2), And it doesn't affect power(5,4) Use
Change the default parameter method
power(6,n=8)
Fallible knowledge : The default parameter must point to unchanged object
def add(L=[])
L.append('END')
return L
# Object is not L The situation of
>>>add([1,2,4])
[1,2,4,'END']
>>>add([2,2,2])
[2,2,2,'END']
# The object is L The situation of
>>>add()
['END']
>>>add()
['END','END']
But every time add There will be one more END, I want to output only one at a time END What to do ?
--- Use None This invariant object
def add(L=None)
if L is None:
L=[]
L.append('END')
return L
6 Variable parameter function *-- Extensible variable
Add... Before the variable *
For example, to use a^2+b^2+c^2+...
def add(*numbers):
sum=0
for n in numbers:
sum+=n*n
return sum
# Of invariant parameters list and tuple It can also become a variable parameter , Just add... Before it *
num=[1,2,3,4]
add[*num]
7 Key parameters **-- Extensible variables and names , optional
#name and sex It's a required option ,00 Optional. , It can also be expanded
# Generally used, optional and required
def person(name,sex,**oo):
print('name:',name,'sex:',sex,'other',oo)
person('a','b',city=' Beijing ',age='7')
>>> name: a sex: b other {'city': ' Beijing ', 'age': '7'}
# Another form of expression , Will be **oo Pull it out alone
ok={'city:':'Beijing','age:':'7'}
person('a','b',city=ok['city'],age=ok['age'])
8 Named key parameters *-- Non extensible values and names , Required
// Only receive city and job As key parameter .
def person(name, age, *, city, job):
print(name, age, city, job)
person('Jack', 24, city='Beijing', job='Engineer')
The practical application is similar to whether there are other ideas in the questionnaire , And the requirements are mandatory
And Key parameters The difference lies in its keyword Can't expand also You can't change the name
9 A small summary
*argc and **kw yes python The customary way of writing
Variable parameters *args, receive 、 What is stored is a tuplelist or tuple func(*(1, 2, 3))
Key parameters **kw, receive 、 What is stored is a dictDirect in func(a=1, b=2)
dict func(**{'a': 1, 'b': 2})
10 Recursive function
n!
def fact(n):
if n==1:
return 1
else:
return n*fact(n-1)
# The hanotta problem
def move(n,a,b,c):
if n==1:
print(a,'-->',c)
else:
move(n-1,a,c,b)# take A above n-1 Move to b
move(1,a,b,c)# take A At the bottom 1 Move to c
move(n-1,b,a,c)# take b above n-1 Move to c
Stack overflow may occur , have access to Tail recursive optimization To solve
11 Iterable
Iteratable object , See if you can use it directly for loop
isinstance(~,Iterable), give the result as follows
Aggregate datalist
、tuple
、dict
、set
、str
generator generator 、 belt yield Function of difference : The difference between generator expressions and list parsing
l=["a"for i in range(10)]
w=(“a” for i in range(10))
12 Common skills
section Get the element at a specific locationAfter taking 10 Elements :L【-10:】
Every time 3 Take one :L【::3】
front 10 Per 2 Take one L【:10:2】
tuple and str It can also be used.
(0,1,2,3,4)【:3】
'ABCDEFG' 【:3】
iteration for indict iteration
iteration key for key in d:
iteration value for values in d.values()
iteration key and value for k,v in d.items()
Iteration string for ch in 'ABC'
Determine if you can iterate isinstance([1,2,3],Iterable)
List Index implementation + Elements for i,v in enumerate([1,2,3])
List builderList data for processing
[ expression for Conditions ]
1 To 10 Number of numbers [i for i in range(1,11)]
x^x An even number of [x*x for x in range(1,10) if x%2==0]
Full Permutation [m+n for m in 'ABC' for n in '123']
for There can be else, But it's an expression ,for The following is the filter condition , Can not have else
generator Calculate the next element according to the algorithm , Than [] Its advantage is that it does not require a lot of storage space
g=(x*x for x in range(1,11))
for n in g: print(n)
# The slicing implementation removes the spaces at the beginning and end of the string
def trim(s):
l=len(s)
if s==l*(' '):
return ''
else:
while s[0]==' ':
s=s[1:]
while s[-1]==' ':
s=s[:-1]
return
#list expression
#100 Number within , Odd numbers are negative numbers , Even is 0
[-x if x%2==1 else 0 for x in range(1,11)]
#generator Function to realize Fibonacci sequence
def fib(max):
n,a,b=0,0,1
while n<max:
yield b
a,b=b,b+a
n+=1
return 'done'
print([x for x in fib(6)])
# Be careful , If you output it directly fib(5) Will return a generator object
# actually , Every time I execute, I encounter yield stop it , Then the next execution is sent to yield From the bottom of
# Yes yield All the signs are generator function
# Yang hui triangle
def triangles():
l=[1]
while(True):
yield l
x=[0]+l
y=l+[0]
l=[x[i]+y[i] for i in range(len(x))]
n = 0
results = []
for t in triangles():
results.append(t)
n = n + 1
if n == 10:
break
for t in results:
print(t)
1 Higher order function
Variables can point to either an object or a function , therefore Function name Can be seen as pointing to a function Variable
Such as def add() m=add
Higher order function : The argument to a function can be another function name
2 map function
effect , Function a set of values Calculation Returns the set of values , Return to one generator object
Format :map(f,l) :f For the function ,l by Iterable Recyclable objects
def f(x):
return x*x
r=map(f,[1,2,3,4,5])
l=list(r) #list() Function let Iterator The object becomes list
print(l)
# It can also be realized with list Functions of the list generator
list(map(str, [1, 2, 3, 4, 5, 6, 7, 8, 9]))
3 reduce function
Equivalent to a recursive function , Calculate the first two parameters each time
# Converts a numeric string to a number
from functools import reduce
d = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
def strtoint(s):
def fn(x,y):
return x*10+y
def charmnum(s):
return d[s]
return reduce(fn,map(charmnum,s))# First of all, will s Traversal usage charmnum Into a digital list, Then recursively add
print(strtoint('123412'))
4 filter() function
effect : Filter Sequence
Format :fileter(f,l)f For one function ,l by Iterable
difference :map It's mainly used to calculate ,filter It is mainly used for filtering
The underlying logic : Each one Iterable Calculate ,True leave False lose
5 sorted() function
Implement sorting
# Normal order
sorted(L)
# In reverse order
sorted(L,reverse=True)
# Sort by specific content , Specific content can be understood as functions , Then there is a return for the value
# Such as sorting by absolute value
sorted(L,key=abs)
# Sort by score
L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]
def by_score(t):
return t[1]
L2 = sorted(L, key=by_score)
print(L2)
L.sort() and sorted(L) Difference of function
L=[1,5,4,54,5]
#sort You must sort on a separate row ,print(L.sort()) The output of is None
L.sort()
print(L)
print(sorted(L))
6 Anonymous functions lambda
effect : The expression is an expression , It can also be considered as the name of a function that does not need to be named , Ready to use . as follows
list(map(lambda x: x * x, [1, 2, 3, 4, 5, 6, 7, 8, 9]))
So we don't need to write a function separately
Of course , Since it's an anonymous function , It is essentially a function , So it can also be assigned to variables , as follows
f = lambda x: x * x
summary : It can be used as a tool , Use with list expressions
7 library
Be careful : The above functions are in Python3 The library needs to be imported in functools
8 Decorator Decorator
pass
9 Partial function
pass
One .py File is a module
mycompany.web
It's also a module , Its file name is __init__.py. There is this module under each package , If not ,python It will be treated as a normal directory instead of a package .
Common standard modules :string、os、sys、time、re、random(random、randint、uniform etc. )、math(sqrt、sin、cos、exp、log)
1 The three major characteristics : encapsulation + Inherit + polymorphic
2 class
# there Object Refers to the parent object , If there is no inheritance, you should still write Object Of
class Student(object):
# Be careful , there __init__ It's the initialization method , The first is always self, When instantiating, you do not need to write self
def __init__(self, name, score):
self.name = name
self.score = score
def print_score(self):
print('%s: %s' % (self.name, self.score))
bart = Student('Bart Simpson', 59)
Pay attention to class writing and initialization
3 Access restrictions -- encapsulation
Purpose : For safety reasons , Or it is more convenient to extend some operations of class attributes , So that the instantiated object cannot be used, such as object .Name Or object .__Name Direct access to
practice : Is to add... Before the attribute __
If you need to visit , Just build a set and get The method is as follows
class Student(object):
def __init__(self, name, score):
self.__name = name
self.__score = score
def get_name(self):
return self.__name
def get_score(self):
return self.__score
Be careful : If you use something like Student.__Name=" Chinese cabbage ", Then print this thing , The result is Chinese cabbage , however , In fact, there is no modification to its internal properties , The underlying logic is to create a new object
In fact, privatization variables can also be obtained , Just use as s1._Studeng__name
therefore ,Python There is no complete privacy in , It just makes it more difficult for you to get attributes
4 Inheritance and polymorphism
Such as class class Student(object): Lieutenant general object Change it to a parent class
class Timer(object):
def run(self):
print('Start...')
Be careful : because python Have the characteristics of dynamic variables , So it doesn't matter what kind you have , As long as you have a method with the same name in this class , You can be Superclass , This feature is called The duck type ( As long as you look like a duck , Can swim , Can walk , Then you are a duck like ).
class Duck:
def quack(self):
print(" Gaga, Gaga .....")
class Bird:
def quack(self):
print("bird imitate duck....")
class geese:
def quack(self):
print("doge imitate duck....")
def in_the_forest(duck):
duck.quack()
duck = Duck()
bird = Bird()
doge = geese()
for x in [duck, bird, doge]:
in_the_forest(x)
Originally forest Only ducks are required , But there are other kinds of ducks quack Methods , So it can also be passed in
5 Get user object information
Judgment variable / Function type type() return Class type Determine the class type isinstance() return True or False Get all the properties and methods of an object dir() return list, It's full of str Determine whether there is a certain attribute or method hasattr() return True or False#type()
>>> type('str')
<class 'str'>
# How to judge the function type ? Import types package , Use the function inside
>>> type(fn)==types.FunctionType
True
>>> type(abs)==types.BuiltinFunctionType
True
>>> isinstance(h, Dog)
True
# It can also be used to judge whether it is one of some classes
>>> isinstance([1, 2, 3], (list, tuple))
True
>>> getattr(obj, 'z', 404) # get attribute 'z', If it doesn't exist , Return default 404
404
hasattr(obj, 'y') # There are properties 'y' Do you ? meanwhile , There are also methods 'y' Do you ?
Be careful :
1 It works type() All judgments can be made isinstance() Judge
2 isinstance Judge the class and its parent class ( Pay attention to the logic )
6 Add class properties and instance properties
# Class properties
class Teacher(object):
name="teacher"
Instance attributes
t=Teacher()
t.sex=' male '
Be careful , The names of class attributes and attributes should not be the same . Add whatever instance attributes you want , Dynamic
7 Add class methods and instance methods
# Define a method , Import MethodType Method , Then call Method Method
from types import MethodType
class Student(object):
pass
s=Student()
def set_age(self, age,name):
self.age = age
self.name=name
s.set_age = MethodType(set_age, s)
s.set_age = 25,'dudu'
print(s.set_age)
# Class binding method
Student.set_age=set_age
8 __slots__
effect : What are the properties and methods of the instance
# Indicates that only the name can be added name and set_age Property or method
class Student(object):
__slots__ =('set_age','name')
Be careful : The properties that subclasses can define are their own __slots__ And the father __slots__
9 @property Decorators
Purpose :
1 It can be used directly student1.score Methods , You can also assign values to conditions
2 Set read and write permissions
3 Make the writing of private variables more concise
# Be careful , first @ It's readable , the second @ It's writable , You still need to initialize to use this
class Screen(object):
def __init__(self, width):
self._width = width
@property
def width(self):
return self._width
@width.setter
def width(self,values):
self._width=values
@property
def height(self):
return self._height
@height.setter
def height(self,values):
self._height=values
@property
def resolution(self):
return self._width * self._height
s = Screen(1024)
s.height = 768
print('resolution =', s.resolution)
if s.resolution == 786432:
print(' The test passed !')
else:
print(' Test to fail !')
Explain why variables are preceded by _, Because this represents a private property , Generally speaking, it needs to pass set and get Method to operate , But it is complicated to operate after instantiation , I still want to use the original student.name To operate , therefore @propert This can be achieved
10 multiple inheritance
practice : As long as object Set to multiple parent objects such as
class Dog(Mammal, Runnable):
pass
11 Enumeration class
effect : In addition to simple enumeration , More importantly, it can be used as Constant
from enum import Enum, unique
@unique
class Weekday(Enum):
Sun = 0 # Sun Of value Be set to 0
Mon = 1
Tue = 2
Wed = 3
Thu = 4
Fri = 5
Sat = 6
# This allows you to access the variable
print(Weekday.Wed.value)
# Variables are immutable , The following is wrong
Weekday.Wed.value=9
12 The metaclass
In addition to using regular creation classes , Use type() It's fine too Create a class
def fn(self):
print("I'm an animal")
Animal=type('Animal',(object,),dict(myself=fn))
dog=Animal()
dog.myself()
type() The three parameters in are
1 Class name
2 Inherited parent class , Be careful One When it comes to parenting tuple() Writing
3 Method
13 metaclass The metaclass
effect : Create a template for the class , That is to say, according to metaclass Create a class , Create instance objects from classes
pass( Generally, I don't use much , It's too hard )
14 zip function
effect : take n Lists are combined into one n Columns of the matrix
a=[1,23,4,5]
b=['e','y','r','d']
for x,y in zip(a,b):
print(x,y)
1 Error handling
try:
print('try...')
r = 10 / int('2')
print('result:', r)
except ValueError as e:
print('ValueError:', e)
except ZeroDivisionError as e:
print('ZeroDivisionError:', e)
else:
print('no error!')
finally:
print('finally...')
print('END')
Be careful : Error is yes Inherit Relational , All mistakes are inherited from BaseException, When multiple errors are thrown , Pay attention to the following errors Bad subclass , because , The parent class will throw the error of the child class .
def foo(s):
return 10 / int(s)
def bar(s):
return foo(s) * 2
def main():
try:
bar('0')
except Exception as e:
print('Error:', e)
finally:
print('finally...')
Of course , When there are multiple levels of nesting , We don't need to write... In every module try catch, Just write it in the key place . if
2 Error throw assert
def foo(s):
n = int(s)
assert n != 0, 'n is zero!'
return 10 / n
Actually sum print perhaps return There's no difference , The efficiency of implementation is not very high
3 logging
import logging
logging.basicConfig(level=logging.INFO)
s = '0'
n = int(s)
logging.info('n = %d' % n)
print(10 / n)
The second line means what kind of Level Error of , Errors have debug
,info
,warning
,error
logging Another advantage is that you can Specify folders Used as a place for your output
1 File read
Underlying principle : The current operating system does not allow the program itself to read files ,python So is the procedure , It sends a request instruction to OS, Give Way OS To read the file . And then python from OS Then get the contents of the file
# Use try finally, The purpose is to close the file even if it is read incorrectly
try:
f = open('/path/to/file', 'r')
print(f.read())
finally:
if f:
f.close()
# Use with, Comparison recommendation , There's no need to write close()
with open('/path/to/file', 'r') as f:
print(f.read())
# Read a line
f.readline()
# Read all , Return to list form , Each element is a line of content
f.readlines()
# Read 5 Bytes
f.read(5)
# Read video 、 Pictures and other binary files , Use open(~,'rb')
f = open('test.jpg', 'rb')
# Read gbk File and ignore errors
f = open('gbk.txt', 'r', encoding='gbk', errors='ignore')
# Use readline Loop through a file
with open('./t1.txt') as f:
while (True):
line = f.readline()
if not line:
break
print(line)
2 File is written to
# Rewrite or create a file
#w It's writing text ,wb Write binary file
with open('test.txt', 'w') as f:
f.write('\nHello, world!')
# Content added , Use 'a'
with open('test.txt', 'a') as f:
f.write('\nHello, world!')
Be careful : Just add 'w' or 'a', If there is no file, it will Automatically create
3 StringIO
Not in the form of a file , But in the form of a string
from io import StringIO
f=StringIO()
f.write("hello")
f.write("world")
print(f.getvalue())
>>> helloworld
# Be careful , Use it directly f.read() It's no use
# Can only be used when there is an initialization form read()
ff=StringIO("hello zjsu")
print(ff.getvalue())
4 BytesIO
Exist in bytes
from io import BytesIO
f = BytesIO()
# Note that you must add encode, If you don't add it, it's just a str Not up to standard
f.write(' chinese '.encode('utf-8'))
print(f.getvalue())
5 serialize , formation JSON Format
import json
d = dict(name='Bob', age=20, score=88)
m=json.dumps(d)
print(m)
Class is JSON format
import json
class Student(object):
def __init__(self, name, age, score):
self.name = name
self.age = age
self.score = score
s = Student('Bob', 20, 88)
print(json.dumps(s, default=lambda obj: obj.__dict__))
# The core idea is to instantiate the class first , Then, the attributes of the class are converted to dict type , Finally, convert it into JSON Format
effect : Implement object serialization
import pickle
class Person:
def __init__(self,n,a):
self.name=n
self.age=a
def show(self):
print self.name+"_"+str(self.age)
aa = Person("JGood", 2)
aa.show()
f=open('d:\\p.txt','w')
pickle.dump(aa,f,0)
f.close()
#del Person
f=open('d:\\p.txt','r')
bb=pickle.load(f)
f.close()
bb.show()
effect : Copy and compression of files, etc
path=os.getcwd()
lst=os.listdir(path)
l=[]
for filename in lst:
if filename.endswith('.py'):
l.append(filename)
# Copy
shutil.copy2(filename, "./question11package")
# Compress
shutil.make_archive("./question11package", "zip","./")
# Traverse all the files in a folder
lst = os.listdir(dirname)
for filename in lst
# Find out everything to .py Final document
if f1.endswith('.txt'):
L.append(f1)
# Find all suffixes
for filename in lst:
listfile.append(os.path.splitext(filename)[1])
effect : Related to sets
from collections import namedtuple
# Represents a two-dimensional coordinate
Point = namedtuple('Point', ['x', 'y'])
p=Point(1,2)
print(p.x)
# Represents a circle
Circle=namedtuple('Circle',['x','y','r'])
p=Circle(4,5,6)
print(p.r)
# Implement a queue or stack
from collections import deque
q = deque(['a', 'b', 'c'])
# Add or delete elements to the end , It's like a stack
q.append('x')
q.pop()
# You can also add or delete elements to the header , Can achieve a two-way list , That is, a two-way queue
q.appendleft('y')
q.popleft()
effect : Related to time and date
from datetime import datetime
# Get current datetime
now = datetime.now()
#str Convert to datetime
cday = datetime.strptime('2015-6-1 18:19:59', '%Y-%m-%d %H:%M:%S')
# Date to str
now = datetime.now()
print(now.strftime('%a, %b %d %H:%M'))
# Get the timestamp ( from 1970 year 01 month 01 Japan 00 when 00 branch 00 Seconds to the present time )
now=time.time()
# The addition and subtraction of time , For example, calculate the time one month ago
prievetime=datetime.date.today()-datetime.timedelta(days=30)
Simple match
# Match a string , Start with three integers + At least one character +5 To 8 Characters
'\d{3}\s+\s{5,8}'
* Arbitrary characters + At least one character ?0 or 1 Characters {n}n Characters {m,n}m To n Characters
Advanced matching
# Match the beginning of a letter or underscore ,19 Character string
[a-zA-Z\_][0-9a-zA-Z\_]{0, 19}
A|B matching A or B^ start $ ending [ ] Within the matching set [^ ] In addition to the collection ( ) Expression grouping re modular
Mode one : Use compile obtain regex Regular expression objects , After use regex.~( character string )
Mode two : direct re.~( Regular expressions , character string )
To put it bluntly, the string is written in one line or two lines
re.match Is to match from the beginning of the string , If the object is returned successfully , Return if failed None
re.search Is to scan the entire string , Returns the first matching object
re.findall Is to scan the entire string , Returns all matching objects
The objects returned are _sre.SRE_Match, have access to m.group() To get specific values
re.match(r'^\d{3}\-\d{3,8}$', s)
re.search(r'^\d{3}\-\d{3,8}$', s)
re.findall(r'^\d{3}\-\d{3,8}$', s)
Cut strings
# Remove spaces from the string with spaces and divide it word by word
>>>re.split(r'\s+', 'a b c')
['a', 'b', 'c']
# With spaces or , or ; String to split
>>> re.split(r'[\s\,\;]+', 'a,b;; c d')
['a', 'b', 'c', 'd']
grouping
function : Split a string into several substring groups
The way :() Inside is the content to be grouped
>>> m = re.match(r'^(\d{3})-(\d{3,8})$', '010-12345')
>>> m
<_sre.SRE_Match object; span=(0, 9), match='010-12345'>
>>> m.group(0)
'010-12345'
>>> m.group(1)
'010'
>>> m.group(2)
'12345'
Greedy matching
form :~+ effect : Match as many characters as possible
Non greedy matching , Is in the + Followed by ? Means to match as few characters as possible
# Greedy matching
>>> re.match(r'^(\d+)(0*)$', '102300').groups()
('102300', '')
# Non greedy matching
>>> re.match(r'^(\d+?)(0*)$', '102300').groups()
('1023', '00')
Match all strings that match the criteria
m=re.findall(r'\[email protected]\w+.\w+',s)
Replace
# Common usage
Find something to use A Days replace all a
re.sub('a','A',s)
# Use the matched group 1 Replace the whole match
re.sub(r'www\.(.*)\..{3}',r'\1',s)
# Use pat take pat Replace the condition in with color
pat=re.compile('(blue|red|white)')
r=pat.sub('color',s)
# Custom function
#?P<> It's fixed writing , Indicates that this group is defined
import re
def add212(matched):
intStr=matched.group("number")
intVal=int(intStr)
addvalue=intVal+212
return str(addvalue)
s="[email protected], [email protected], [email protected]"
m=re.sub("(?P<number>\d+)",add212,s)
print(m)
Environment configuration : Configure mirror source
pip install pip -U
pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple
6 Official functions
Built-in Functions — Python 3.9.10 documentation
When reading a file UnicodeDecodeError: 'gbk' codec can't decode byte 0x80 in position 9: ...
reason : Coding errors
Solution
with open ('demo.txt','r',encoding='utf-8') as file:
Shortcut key
double Shift Omnipotent search Ctrl+Alt+L format Ctrl+Alt+N Jump to a page Ctrl+E Recent documents Crtl+Shift+F Search for something on this page Ctrl+Shift+R replaceCtrl+Shift+A
Input split v
Split screenExercises
Python course - Liao Xuefeng's official website (liaoxuefeng.com)