Python common syntax

Posted by nashsaint on Mon, 24 Jan 2022 18:40:53 +0100


This article aims to record some grammars frequently used by the author in his daily use of Python, which are constantly updated. Some of them refer to some references from Zhihu, CSDN and other channels. If there are any similarities, please forgive me and communicate with the author in private.

1. String (str)

1.1. add to

1. Direct addition
2. Center aligned fill

str0.center(width, fillchar)#Returns a string centered on the specified width. fillchar is the filled character. The default is space.

3. Left aligned fill

str0.ljust(width[, fillchar])#Returns a new string with the original string left aligned and length width. fillchar is the padding character, and the default is space.

4. Right align fill

str0.rjust(width,[, fillchar])#Returns a new string with the length of width aligned to the right of the original string. fillchar is the padding character, and the default is space

1.2. delete

1. Circularly delete the specified characters on the right

str0.rstrip(chars)#Delete the specified character char (all) to the right of the string

2. Circularly delete the specified characters on the left

str0.lstrip(chars)

#Deletes the specified character to the left of the string
3. Circularly delete the specified characters on the left and right sides
str0.strip(chars) # deletes the specified characters on the left and right sides of the string
For example:

str0 = "88888888this is string example....wow!!!8888888";
print(str0.rstrip('8'))#88888888this is string example....wow!!!

1.3. retrieval

str0.find(str, beg, end)#Check whether str0 is in the range of string beg to end. If it is the index value that appears for the first time, otherwise - 1 will be returned, and all ranges will be returned by default
str0.rfind(str, beg, end)#Search from the right, and the index order is consistent with the original string
str0.index(str, beg, end)#It is the same as the find() method, except that if str is not in the string, an exception will be reported.
str0.rindex(str, beg, end)#Search from the left, and the index order is consistent with the original string

1.4. Statistics

str0.count(str, beg,end)#Returns the number of times str0 appears in the range from beg to end in the string. The default range is all

1.5. List string to string conversion

1.5.1. List - > string

list0=['1', '2', '3', '4', '5']
str0=' '.join(list0)#Used to connect the elements in the sequence list0 with the specified character '' to generate a new string
print(str0)#'12345'

1.5.2. String - > List

1. Direct conversion

str0 = "12345"
list0 = list(str0)
print(list0)#['1', '2', '3', '4', '5']

2. Split by element

str_name.split(str, num)#str: separator, which defaults to all empty characters, including spaces, line breaks (\ n), tabs (\ t), etc. num: the number of divisions. The default value is - 1 to separate all.

For example:

str0 = "www.google.com"
list0 = str0.split(".")
print(list0)#['www', 'google', 'com']

3. Split by line

splitlines(keepends)#Separated by rows ('\ r', '\r\n', \n '), returns a list containing rows as elements. If the parameter keeps False, it does not contain line breaks. If it is True, it retains line breaks.

For example:

'abc\n\ndefg\rkl\r\n'.splitlines()		#['abc', '', 'defg', 'kl']
'abc\n\ndefg\rkl\r\n'.splitlines(True)	#['abc\n', '\n', 'defg\r', 'kl\r\n']

1.6. Case

1. In figures

str0.lower()#Converts all uppercase characters in string str0 to lowercase.

2. In words

str0.upper()#Converts lowercase letters in the string str to uppercase.

3. Capitalize the first character

str0.capitalize()#Converts the first character of the string str to uppercase

4. Titling

str0.title()#Return str0 to the "captioned" string, that is, all words start with uppercase and the rest are lowercase

For example:

str0 = "this is string example from runoob....wow!!!"
print (str0.title())#This Is String Example From Runoob....Wow!!!

1.7. judge

1. Digital judgment

str0.isdigit()#Returns True if the string contains only numbers; otherwise, returns False.

2. Case judgment

str0.islower()#Returns True if the string str has at least one character and all characters are lowercase; otherwise, returns False.
str0.isupper()#Returns True if the string str has at least one character and all characters are uppercase; otherwise, returns False.

3. Blank judgment

str0.isspace()#Returns True if the string contains only white space; otherwise, returns False.

4. Title Judgment

str0.istitle()#Returns True if the string is captioned (see title()), otherwise returns False.

1.8. replace

str0.replace(old, new [, max])#Replace old in the string with new. If max is specified, the replacement shall not exceed max times.

2. List

2.1. add to

1. Expand multiple elements

list0.extend([seq])#Append multiple values in another sequence at the end of the list at one time (expand the original list with the new list)

2. Insert

list0.insert(index, element)#Insert object into list

3. Direct addition to realize splicing

2.2. Delete list element

1. According to the index

del list0[index] 

2. According to the element value

list0.remove(element)#Delete first match

3. Pop up

element=list0.pop(index=-1)#Removes an element from the list (the last by default) and returns the value of that element

2.3. retrieval

list0.index(element)#Find the index position of the first matching item of a value from the list. If it is not found, an error will be reported

2.4. Statistics

list0.count(element)#Counts the number of times an element appears in the list

2.5. Extract qualified elements from sequences (strings, lists, etc.)

filter(function, iterable)#Function: judge the function, and the return value is true or false. Iteratable: iteratable object.

Filter out all odd numbers in the list

newlist = list(filter(lambda x:x%2==1, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))#filter is a pointer, which needs to be converted from list to list [1, 3, 5, 7, 9]

Filter out all numbers in the string

newlist=list(filter(lambda x,x.isdigit(), '123ab45'))#filter is a pointer, which needs to be converted from list to list ['1', '2', '3', '4', '5']

2.6. List assignment

1. Single assignment

x=[[0 for i in range(2)] for i in range(3)]#[[0, 0], [0, 0], [0, 0]]
x[1][1]=1#[[0, 0], [0, 1], [0, 0]]

Matrix = [[] for x in range(3)]#[[], [], []]

2. Overall assignment

x=[[0]*2]*3#Change one column and change all columns
x[1][1]=1#[[0, 1], [0, 1], [0, 1]]

3. Slice

list0[1,2]#No, it should
list0[1][2]

2.7. Invert

list0.reverse()#Elements in reverse list

2.8. sort

list0.sort( key=None, reverse=False)#The key function filters the elements participating in sorting. reverse=True descending, False ascending

For example:

random = [(2, 2), (3, 4), (4, 1), (1, 3)] 
random.sort(key=lambda element:element[1])#Specifies the second element sort
#[(4, 1), (2, 2), (1, 3), (3, 4)]

2.9.map() maps the specified sequence according to the provided function

list(map(lambda x: x ** 2, [1, 2, 3, 4, 5]))#[1, 4, 9, 16, 25]

3. Heap is similar to list

4. Queue is similar to list and has more functions than list

from collections import deque
dlist=deque([1,'a'])

4.1. add to

dlist.append('b') # Add data [1,'a', 'b'] at the end
dlist.appendleft(0) # Insert data at the front end#[0,1,'a', 'b']
dlist.extend(['c','d']) # Append at the end list data#[0,1,'a', 'b','c','d']
dlist.extendleft([-2,-1])# Insert list data [- 2,-1,0,1,'a', 'b','c','d '] in the front end

4.2. delete

dlist.pop() # Delete end data#[-2,-1,0,1,'a', 'b','c']
dlist.popleft() # Delete front-end data#[-1,0,1,'a', 'b','c']

4.3. Batch move

dlist.rotate(-2) # Move the element at the left end to the right end
print(dlist)# Output: deque (['a ', 555, - 1, 0,' C ',' B '])
dlist.rotate(2) # Move the element at the right end to the left end
print(dlist)# Output: deque (['c ',' B ',' a ', 555, - 1, 0])

5. Tuple

5.1. add to

1. Direct addition
2. Splicing

x=(('1')*4)*2#(('1','1','1','1'),('1','1','1','1'))
#A reference is similar to a list and can be multidimensional, but the value cannot be modified

6. Dictionary (dict)

6.1. add to

1. Initialization
A = {} dictionary a[1]=1
A = [] list cannot be a[1]=1
2. Batch creation

dict.fromkeys(seq[,value])#Create a new dictionary, use the elements in seq list as dictionary keys, and value is the initial value corresponding to all dictionary keys

3. Batch add

dict1.update(dict0)#Update the key / value pair of dictionary dict0 to dict1

6.2. delete

del dict0['key']#Delete pairs according to key
value=pop(key)#Delete the pair corresponding to the key given in the dictionary, and the return value is the deleted value.
item=dict0.popitem()#Deletes the last pair of keys and values in the dictionary and returns the pair (no parameters in parentheses).

6.3. ergodic

for key,values in dict0.items(): 
for key in dict0.keys():
key in dict0.keys()#If the key returns true in dictionary dict0, otherwise it returns false
for value in dict0.values():
value in dict.values()#Return true if the value is in the dictionary dic0t, otherwise return false

6.4. Inversion

d=[('a', 1), ('c', 3), ('b', 2)]
d1=dict([k, v] for k, v in d.items())#d1[('1', a), ('3',c ), ('2',b )]

6.5. Type conversion

dict0={'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
print(type(dict0))#Returns the input variable type < class' dict '>
print(str(dict0))#Output dictionary, represented as a printable string. {'Name': 'Runoob', 'Age': 7, 'Class': 'First'} 	

7. Assembly

7.1. Add element

s= set()
s.add('element')#Add a single element, {'element'}
s.update({1,2},[3,4],{5:6},"7")#Add lists, tuples and dictionaries, and separate multiple with commas, {'element',1,2,3,4,5}

7.2. Removing Elements

s.discard( x )#Removes the element from the collection, and if the element does not exist, no error occurs.
s.pop()#The set is arranged unordered, and then the first element on the left of the unordered set is deleted.

7.3. basic operation

1. Assignment

a={'a','b','r','a'}
#perhaps
a = set('abra')#{'a', 'r', 'b'} automatic weight removal

2. Operation

element in basket # Quickly determine whether the element is in the set basket                         
a - b#{'R','b '} elements contained in set a but not in set B                        
a | b#{'a', 'r', 'b', 'l'}                   
a & b# {'a'}               
a ^ b#{'r', 'b', 'l'}

3. Similar to list derivation, set derivation is also supported

a = {x for x in 'abracadabra' if x not in 'abc'}#{'r', 'd'}

8. Similarities

1. Empty copy
clear() copy() # list dictionary sets have empty copy operations, tuples and strings do not
2. Maximum and minimum
max(),min() # string list tuple
3. Len(), enumerate (keys and subscripts in the dictionary) all five

enumerate(sequence, [start=0])#It is used to combine a traversable data object into an index sequence and list data and data subscripts at the same time. It is generally used in the for loop
#Sequence: a sequence, iterator, or other object that supports iteration.
#Start: subscript start position.
index=[i for i,x in enumerate(a) if x == 1 ]

9.end keyword

print(1,end=',')#Used to output the results to the same line, or add different characters at the end of the output
print(2,end=',')
#1,2,

10. Circulation

1

for i in range(-10, -100, -30) :#Excluding 100 
	print(i)
#-10 -40 -70

2

count = 0 
while count < 3: 
	print (count, " Less than 3") 
	count = count + 1 
else: 
	print (count, " Greater than or equal to 3")
#0 less than 3
#1 less than 3
#2 less than 3
#3 greater than or equal to 3

11. Iterators and generators

11.1. Two ways to create iterator objects

1. Create directly

it=iter(seq)#seq can be five, and the words in the dictionary are for keys
it = iter([1,2,3,4])    	 # Create iterator object
print (next(it))#1   # The next element of the output iterator
print (next(it))#2

2. yield in function

def func(max):
	i=1
    while i<max:
        i=i+1   
        yield i  
it=func(5)

11.2. Call iterator

1. Loop traversal

for x in it:
    print (x, end=" ")
#1 2 3 4

2. Direct reading

x1,x2,x3,x4=it
print(x1,x2,x3,x4)

3. Introduce sys module

import sys # Introducing sys module 
while True:
    try:
        print (next(it))
    except StopIteration:
        sys.exit()

12. Function

12.1. Add (: data type) after the formal parameter to specify the data type of the formal parameter

12.2. Changeable and unchangeable objects

strings, tuples, and numbers are immutable objects, while list,dict, etc. are modifiable objects.
Modifying the incoming list directly in the function will change the list outside the function. It is best to create another list in the function for storage, because the incoming reference is the reference of the argument. And strings and so on will not change.

12.3.*

1. ∗ * * separate the elements in list, tuple, Dictionary (key), set and numpy into independent elements one by one

List = ['a', 2, 3]#*List:a 2 3
Tuple = ('b', 'c', 5)#*Tuple :b c 5
Dict = {'name': 'Ada', 'age': 23}#*Dict:name age
ndarray = np.array([2, 3, 4])#*ndarray:2 3 4

2. ∗ * * use of args parameter

def fun(*args):#When multiple location parameters are passed in, they will automatically form a tuple
    print(args)
fun(2, 'alex', [3])#(2, 'alex', [3]) 

3. ∗ ∗ ** * use of kwargs formal parameters

def fun(**kwargs):#When multiple keyword parameters are passed in, the multiple location parameters will automatically form a dictionary
    print(kwargs)  
fun(name='Alvin', age=23, things=[1, 2, 'a'])#{'name': 'Alvin', 'age': 23, 'things': [1, 2, 'a']}

13. Input and output

1. Standardized output

print('constant pi The value of is approximately {:.3f},e The value of is:{:.3f}. '.format(math.pi,math.e))#. 3 after the colon means three decimal places are reserved. After the colon, b binary d decimal o octal x hexadecimal
#Old edition 
print('constant pi The approximate value of is:%5.3f,e The value of is:%5.3f. ' % (math.pi,math.e))

2. Keyboard input

str = input("Please enter:");#The input is automatically converted to a string
print ("What did you enter: ", str)
#Please enter: rookie tutorial
#The content you entered is: rookie tutorial

14.import os

1. Read the names of all pictures in the folder in a fixed order with suffixes

data  =os.listdir(dirc)#dirc is the path of the folder where the pictures are located  

2. Rename

os.rename(old,new)

3. Get directory

print(os.getcwd())#Get current directory
print(os.path.abspath(os.path.join(os.getcwd(), "..")))#Get parent directory
print(os.path.abspath(os.path.join(os.getcwd(), "../..")))#Get parent directory
print(os.path.abspath(os.path.join(os.getcwd(), "../../..")))#Get parent directory

4. Slice the path

os.path.splitext("File path+file name+"Suffix")#Separate (file path + file name) and suffix, and return (fname,fextension) tuples by default,
os.path.split("File path+File name)  #Separate file path and file name

5. Traversal (only access to folders)

for root, dirs, files in os.walk(dir):
        # root indicates the folder path currently being accessed. root traverses dir from depth to breadth, that is, first dir, traversing the folder in dir, and then traversing the folder in dir.
        # dirs indicates the folder name under the folder folder	
        # files indicates the file name under the folder file

6. Create a path

def makedir(path):#
    if not os.path.exists(path):#Determine whether the path exists
        os.makedirs(path)

7. Clear all files in the path

def clear_images(path):#
    names=os.listdir(path)
    for name in names:
        os.remove(os.path.join(path,name))

15. Naming

1. The global function modifies global variables internally. As long as they are global variables, they can only be global

num = 1
def fun1():
    global num  # global keyword declaration is required
    print(num) #1
    num = 123
    print(num)#123
fun1()
print(num)#123

2.nonlocal modify variables in nested scope (enclosing scope, outer non global scope)

def outer():
    num = 10
    def inner():
        nonlocal num   # nonlocal keyword declaration
        num = 100
        print(num)#100
    inner()
    print(num)#100

16. Object oriented

16.1. modular

1.if name = = 'main': operation principle of

if __name__ == '__main__':
   print('The program itself is running')
else:
   print('The first mock exam is from another module.')

2.dir() function

dir('Module name') #You can find all the names defined in the module. Returns as a list of strings. If there are no parameters in (), list all module names of the current program.

3.init.py module
If the directory contains init Py, when importing the directory with import, init Py inside the code

4. Standard modules and packages are temporarily unavailable

16.2. attribute

1. Instance attribute and class attribute

#Instance properties are owned by each instance and independent of each other, while class properties have and only one copy.
class Circle:
   pi = 3.14  # Class properties
   def __init__(self, r):
       self.r = r#Instance properties
C=Circle(1)
C.pi=3 #Create an instance attribute with the same name as the class attribute for circle1, which takes precedence over the class attribute
print(Circle.pi,C.pi)#3.14,3
del C.pi
print(Circle.pi,C.pi)#3.14,3.14

2. Class methods must contain self
3. Private property
Add two underscores before the class attribute to declare that the attribute is private and cannot be used or accessed directly outside the class.
4. Private method
Add two underscores before a class method (function) to declare that the method is private and can only be called inside the class, not outside the class.
5. Instance properties can be created directly outside the class

16.3. inherit

1. Calling sequence
Inherit multiple parent classes class son(father1, father2, father3...):
When there are the same methods in father1 and father2, call the first father1
2. Subclasses are not overridden__ init__ () method

#Subclasses do not override__ init__ () method. After instantiating a subclass, it will automatically call the parent class__ init__ () method.
#Subclass override__ init__ () method. After instantiating a subclass, the parent class will not be called automatically__ init__ () method.
class father:
    def __init__(self,a):
        self.a=a
class son(father):
    def p(self):
        print('Parent class self.a:',self.a)
s=son(1)
s.p()

3. Subclass override__ init__ () method needs to call the parent class__ init__ () method

#Use the super keyword:
class father:
    def __init__(self,f):
        self.f=f
class son(father):
    def __init__(self,s,f):
        super(son,self).__init__(f)#Fill in the parent parameter list in parentheses
        print('Parent class self.f:',self.f)#Parent class self f: father
        self.s=s
        print('Subclass self.s:',self.s)#Subclass self s: son
son('son','father')

4. Subclass overrides other methods of parent class

Son =son() # Subclass instance 
Son.Method() #When calling a subclass, call the subclass method first. If there is no such method, it will be found in the parent class
super(son,Son).Method() #Call a method whose parent class has been overridden with a subclass object

16.4. method

1. Class method
A method that can be accessed without instantiating a class.
@classmethod decoration
@classmethod decorated methods cannot use instance properties, but only class properties. It is mainly used in function methods that interact with classes but not with their instances.

class Circle:
   __pi = 3.14
   @classmethod#Only one function after this symbol is a class method
   def pi(cls,x):#,x):#After cls, you can also pass in parameters, enter corresponding values when calling, and reconstruct class properties through this
        print(cls.__pi)
        print(x)
Circle.pi(1)#3.14,1

@staticmethod decoration
@Staticmethod is very similar to @ classmethod, but @ staticmethod does not require parameters to be passed (it does the same thing as class methods or instance methods)@ Static method is used in some class related functions, but does not use the class or instances of the class. Use, such as changing environment variables, modifying properties of other classes, etc@ The method modified by staticmethod is a function placed outside the class. We moved it to the class for convenience. It has no impact on the operation of the class.

class Circle:
    __pi = 3.14
    @staticmethod
    def f(arg1, arg2, ...):

@property decoration
Converts a class method to a read-only class property

class Circle:
   __pi = 3.14
	@property
	   def pi(self):
	       return self.__pi

2. Construction method
__ new__ Concept:
Call first__ new__ Create an instance, which only takes down the cls parameter and passes other parameters to__ init__, When the life cycle of this object ends__ del__ Will be called.
__ new__ In__ init__ Previously called:

class Animal:
    def __new__(cls, *args, **kargs):
        print("do __new__")
        return object.__new__(cls, *args, **kargs) # If no instance is returned, the__ init__
    def __init__(self):
        print("do __init__")
animal = Animal()
#do __new__
#do __init__

Override int class:

class PositiveInteger(int):
    def __new__(cls, value):
        return super(PositiveInteger, cls).__new__(cls, abs(value))
    def __init__(self,value):
        self.value = value
i = PositiveInteger(-3.2)
print(i)#-3.2
print(i.value)#3

Single example:
__ new__ The return value (instance) of will be passed to__ init__ Method, and then__ init__ Set some parameters for this instance to return the parent class__ new__ The instance or object__ new__ Out of the example.

class Singleton:
    __instance = None
    def __new__(cls, age, name):
        print(cls.__instance)
#None
#<__main__.Singleton object at 0x7f9fb7693e10>
#If__ If instance has no or no assignment, an object is created and assigned as a reference to this object
#When this method is called again, it returns the previously created object, which ensures that there is only one object
        if not cls.__instance:
            cls.__instance = object.__new__(cls)
        return cls.__instance
    def __init__(self,age,name):
        self.age = age
        self.name =name
a = Singleton(18, "xxx")
b = Singleton(8, "xxx")
print(id(a))#140323953655312
print(id(b))#140323953655312
print(b.age)#Get the age attribute of the object pointed to by b, 8

Delete:

def __del__(self):#This statement is automatically executed when del deletes class instance name, class instance attribute and class attribute

5. Representation of classes
str:

def __str__(self):
	return#Must be in string format
	#When you use print to output an object, as long as you define it yourself__ str__(self) method, the string return ed from this method will be printed.

repr:

def __repr__(self):
	return #Must be in string format
 #Like str, it is applicable to terminal or stream output < < instance name

format:

class people:
    def __init__(self,name,age):
        self.name,self.age=name,age
    def __format__(self,specification):
        if specification=="":
            return str(self)
        return specification.replace("%s",self.name).replace("%r",self.age)
        
peopleobj=people('zhangsan','31')
print("{}".format(peopleobj))#<__main__.formattest object at 0x000001D013F8F248>
print("{0:%s-%r}".format(peopleobj))#zhangsan-31

class hand:
    def __init__(self,*people):
        self.peoples=list(people)
    def __format__(self,specification):
        if specification=="":
            return str(self)
        return ",".join("{:{fs}}".format(c,fs=specification) for c in self.peoples)

handobj=hand(people("zhangsan","18"),people("lisi","28"))
print("{}".format(people))#<class '__main__.people'>
print("{0:%s-%r}".format(handobj))#zhangsan-18,lisi-28

other:

def __unicode__(self):
def __hash__(self):
def __nonzero__(self):
def __dir__(self):

6. Access control (adding and deleting attributes)
__ setattr__(self, key, value)
It can be used for real packaging. It allows you to customize the assignment behavior of an attribute, whether the attribute exists or not, that is, you can define your own rules for any change of any attribute.
__ getattribute__(self, item)
__ getattribute__ It seems to work well with the above methods, but it's best not to use it__ getattribute__ Can only be used for new classes. In the latest version of Python, all classes are new classes. In the old version of Python, you can create new classes by inheriting object s__ getattribute__ It allows you to customize the behavior when attributes are accessed, and it may also encounter infinite recursion problems (by calling getattribute of the base class)__ getattribute__ Basically can replace__ getattr__. It is used only when it is implemented and explicitly called, or when AttributeError is generated. This magic method can be used (after all, the choice is up to you). I don't recommend you to use it because its scope of use is relatively limited (usually we want to carry out special operations during assignment rather than value), and it is easy to get bugs when implementing this method.
__ getattr__(self, item):
When a user tries to access a property that does not exist at all (or temporarily does not exist), you can use this magic method to define the behavior of the class. This can be used to catch misspellings and give guidance, give warnings when using obsolete attributes (you can still calculate and return the attribute if you like), and flexibly handle AttributeError. It is called only when trying to access a non-existent property, so this is not a real encapsulation.
__ delattr__(self, item)
This magic method and__ setattr__ Almost the same, except that it is used to handle the behavior when deleting attributes.

class person:
    def __init__(self,name):
        self.name=name
    def __setattr__(self, key, value):
        print("do __setattr__")
        object.__setattr__(self,key,value)
    def __getattribute__(self, item):
        print("do getattribute")
        return object.__getattribute__(self,item)
    def __getattr__(self, item):
        try:
            print("do getattr")
            return object.__getattribute__(self,item)
        except:
            return "Not find attribute:{}".format(item)
    def __delattr__(self,item):
        print("do delattr")
        object.__delattr__(self,item)
personobj=person("Li")#do __setattr__
print(personobj.name)#do getattribute #Li
print(personobj.age)#do getattribute #do getattr #Not find attribute:age
personobj.age=27#do __setattr__
print(personobj.age)#do getattribute #27
delattr(personobj,"age")#do delattr
print(personobj.age)#do getattribute #do getattr #Not find attribute:age

7. Reflection (not commonly used)

8. Custom sequence
List:

#list
class List:
    def __init__(self, values=None):
        if values is None:
            self.values = []
        else:
            self.values = values
    def __getitem__(self, key):#Defines the behavior when reading an item in the container using the self[key] method, and the methods to be implemented for both variable and immutable container types
        return self.values[key]#It should generate TypeError exception when the type of key is wrong, and KeyError exception when there is no content matching the key value.
        
    def __setitem__(self, key, value):#Defines the behavior when assigning a value to an item in the container using the self[key] method. Is a method that a variable container type must implement
        self.values[key] = value      #KeyError and TypeError exceptions should also be generated when appropriate.
    
    def __len__(self):                #Return the length of the container. Both variable and immutable types need to be implemented.
        return len(self.values)
    
    def __delitem__(self, key):
        del self.values[key]
        
    def __iter__(self):               #Returns an iterator
        return iter(self.values)
    
    def __reversed__(self):
        return reversed(self.values)  #Returns an iterator of a reverse sequence
    
    def append(self, value):
        self.values.append(value)
    def first(self):
        return self.values[0]
    def last(self):
        return self.values[-1] 
    def front_section(self, n):
        return self.values[:n]
lis= List([1,2,3,4,5,6])
print(lis[0])#1
lis[0]=100#[100,2,3,4,5,6]
print(len(lis))#6
del lis[0]#[2,3,4,5,6]
it=iter(lis)
print(next(it))#2
print(next(it))#3
print(list(reversed(lis)))
lis.append(7)#[2,3,4,5,6,7]
print(lis.first())#2
print(lis.last())#7
print(lis.front_section(3))#[2, 3, 4]

Dictionaries:

class A(object):
    a = 0
    b = 1
    def __init__(self):
        self.a = 2
        self.b = 3
obj = A()
print(obj.__dict__)#{'a': 2, 'b': 3}
class Dictionary:
    def __setitem__(self, key, value):
        self.__dict__[key] = value

    def __getitem__(self, key):
        return self.__dict__[key]

    def __delitem__(self, key):
        del self.__dict__[key]
diction = Dictionary()
diction["one"] = 1
diction["two"] = 2
print(diction['two'])#2
del diction['two']
print(diction['two'])#KeyError: 'two'

Container:

class Contain:
    def __init__(self, data):
        self.data = data
        
    def __contains__(self, x):
        return x in self.data
contain = Contain([2,3,4,5])
#When we call if 2 in contain__ contains__ This special method returns a Boolean value through the statement in the method.
if 2 in contain:
    print("2 stay contain in")#2 in the contain
if 6 not in contain:
    print("6 be not in contain in")#6 is not in the contain

9. Abstract base class
As a kind of inheritance, abstract base class has the advantages of inheritance, but it is also different from ordinary inheritance:
Abstract base class cannot be instantiated
Subclasses need to implement the abstract methods specified by the base class
Imagine a scenario: when you develop a project or service, you need to provide interfaces for upstream and downstream components and let others call your Application Programming Interface (API). How can upstream and downstream components achieve the desired purpose and seamlessly connect with your components? It needs to be implemented according to the abstract methods specified in your interface. For example, you provide an interface to access network requests. You will not register and send requests for host, username and password. These users need to call. You only need to specify that "the caller must implement the specified method to call".

from abc import ABC
from abc import abstractmethod


class Database(ABC):
    def register(self, host, user, password):
        print("Host : {}".format(host))
        print("User : {}".format(user))
        print("Password : {}".format(password))
        print("Register Success!")

    @abstractmethod
    def query(self, *args):
        """
        Of incoming query data SQL Statement and execute
        """

    @staticmethod
    @abstractmethod
    def execute(sql_string):
        """
        implement SQL sentence
        """
class Component1(Database):
    def __init__(self, host, user, password):
        self.register(host, user, password)

    @staticmethod
    def execute(sql_string):
        print(sql_string)

    def query(self, *args):
        sql_string = "SELECT ID FROM db_name"
        self.execute(sql_string)


class Component2(Database):
    def __init__(self, host, user, password):
        self.register(host, user, password)

    @staticmethod
    def execute(sql_string):
        print(sql_string)

    def query(self, *args):
        sql_string = "SELECT NAME FROM db_name"
        self.execute(sql_string)

comp1 = Component1("00.00.00.00", "abc", "000000")#Host : 00.00.00.00#User : abc#Password : 000000#Register Success!
comp2 = Component2("11.11.11.11", "ABC", "111111")#Host : 11.11.11.11#User : ABC#Password : 111111#Register Success!
comp1.query()#SELECT ID FROM db_name
comp2.query()#SELECT NAME FROM db_name

10. Function call
When we add special methods to a class__ call__ After that, when we call with the instance name, it will enter the__ call__ Method, execution__ call__ Program in.
nn.Module is the base class of all neural network modules, and pytorch is in NN Module, which implements__ call__ Method, and in__ call__ The forward function is invoked in the method.

class A:
    def __init__(self, age):
        self.age = age
        print('call__init__')
    def __call__(self, added_age):
        print('call__call__')
        res = self.forward(added_age)
        return res
    def forward(self, input_):
        print('call forward')
        return input_ + self.age
a = A(10)#Call__ init__
input_param = a(2)#call__call__#Call forward
print("My current age is:", input_param)#My age now is: 12

11. Context manager (special method of class implementing with)
The instance is returned after the initialization of enter. exit handle when exiting, such as clearing memory, closing files, deleting redundancy, etc
The program first goes to the init method for initialization, then automatically enters the enter special method, then calls the read() method through fr.read, and finally calls the exit method when exiting.

class FileReader:
    def __init__(self):
        print("in init method")
    def __enter__(self):
        print("in enter method")
        return self
    def read(self):
        print("in read method")#with statement call
    def __exit__(self, exc_type, exc_value,exc_tb):
        print("in exit method")
        del self
with FileReader() as fr:
    fr.read()
    #in init method 
    #in enter method
    #in read method
    #in exit method

12. Create descriptor object

class descriptor:
    def __get__(self, instance, owner):
        print("do get")
        print(instance)
        print(owner)
        return "desc"
    def __set__(self, instance, value):
        print("do set")
        print(instance)
        print(value)
    def __delete__(self, instance):
        print("do del")
        print(instance)
class A:
    a=descriptor()
print(A().a)#do get #<__main__.A object at 0x000002782377F248> #<class '__main__.A'> #desc
A().a=5#do set #<__main__.A object at 0x000001D8E72DF248> #5
del A().a#do del #<__main__.A object at 0x0000027E472BF288>
A.a=5#Directly modify the class variable of class A, that is, a is no longer represented by the descriptor descriptor

13. Copy

import copy

class Mobile:
    def __init__(self,cpu,screen):
        self.cpu=cpu
        self.screen=screen
class Cpu:
    def caculate(self):
        print("cpu Execute calculation program")
class Screen:
    def show(self):
        print("Screen display")
        
c1=Cpu()
c2=c1

#Variable assignment
print(c1)#<__main__.Cpu object at 0x0000022F8B90F548>
print(c2)#<__main__.Cpu object at 0x0000022F8B90F548>

#Shallow copy
s1=Screen()
m1=Mobile(c1,s1)
m2=copy.copy(m1)
print(m1)#<__main__.Mobile object at 0x00000168B33FF808>
print(m2)#<__main__.Mobile object at 0x00000168B33FFF08>
print(m1.cpu)#<__main__.Cpu object at 0x00000168B33FF6C8>
print(m2.cpu)#<__main__.Cpu object at 0x00000168B33FF6C8>

#Deep copy
m3=copy.deepcopy(m1)
print(m1)#<__main__.Mobile object at 0x0000027CEBC4F908>
print(m3)#<__main__.Mobile object at 0x0000027CEBC4F8C8>
print(m1.cpu)#<__main__.Cpu object at 0x0000027CEBC4F7C8>
print(m3.cpu)#<__main__.Cpu object at 0x0000027CEBC52048>

14.pickle
Storage:

import pickle 
data = {'foo': [1,2,3], 'bar': ('Hello', 'world!'), 'baz': True} 
jar = open('data.pkl', 'wb') 
pickle.dump(data, jar)#Write pickle d data into jar file
jar.close()

Take:

import pickle 
pkl_file = open('data.pkl', 'rb')# Data connection after pickle
data = pickle.load(pkl_file)#Load it into a variable
print(data)
pkl_file.close()

Save a class, read it later, and use it directly:

import pickle
class person:
    def __init__(self):
        self.name="cai"
personobj=person()
with open("person.txt",'wb') as f:
    #Store after serialization
    pickle.dump(personobj,f)
with open("person.txt",'rb') as f:
    #Reverse sequencing
    p=pickle.load(f)
    print(p.name)#cai

pickle object:

import pickle
class person:
    def __init__(self,name):
        print("do __init__")
        self.name=name
    def __getnewargs__(self):
        print("do __getnewnewargs__")
        return "wang",
    def __getstate__(self):
        print("do __getstate__")
        return {"name":"xiao"}
    def __setstate__(self,state):
        print("do __setstate__")
        print(state)
        self.__dict__=state
personobj=person("cai")#do __init__
with open("person.txt",'wb') as f:
     #Store after serialization
     pickle.dump(personobj,f)#do __getnewnewargs__ #do __getstate__
with open("person.txt",'rb') as f:
    #Reverse sequencing
    p=pickle.load(f)#do __setstate__ #{'name': 'xiao'}
    print(p.name)#xiao

15. Arithmetic operation

16. Comparison operation

17. Other operations

17. Common functions

1.random

2. Timing

import time
start = time.perf_counter() 
end = time.perf_counter() 

3.id function
id# access the address of the variable object

18. Reading and writing documents

1. Open

seq = ["Rookie tutorial 1\n", "Rookie tutorial 2"]
Two ways to open a file
f=open("/tmp/foo.txt", "w",encoding='utf-8') 
with open("/tmp/foo.txt", "w",encoding=	'utf-8')as f:#Open file
f=open()
#After the f reference of the latter, f.close() will be executed automatically, that is, f is invalid and can no longer be referenced

2. Reading

string=f.read(size)#size indicates the number of characters to read. It is not set to read all by default
string=f.readline()#Read one line without line breaks \ n
string=f.readlines()#Read all lines, display line breaks \ n, and store a string in each line in the list

3. Write

f.write("Python Is a very good language.\n I like it Python!!\n")
f.writelines(seq)#Each element in seq is written as a line

19. Errors and exceptions

19.1 exception capture

try:
    # Code attempted to execute
    pass
except Error type 1:
    # Corresponding code processing for error type 1
    pass
except Error type 2:
    # Corresponding code processing for error type 2
    pass
except (Error type 3, Error type 4):
    # Corresponding code processing for error types 3 and 4
    pass
except Exception as result:
    # Print error message
    print(result)
else:
    # Code that executes without exceptions
    pass
finally:
    # Code that will be executed whether there is an exception or not
    print("Code that executes regardless of whether there are exceptions")
try:
    num = int(input("Please enter an integer:"))
    result = 8 / num
    print(result)
except ValueError:
    print("Please enter the correct integer")
except ZeroDivisionError:
    print("Divide by 0 error")
except Exception as result:
    print("unknown error %s" % result)
else:
    print("Normal execution")
finally:
    print("The execution is complete but not guaranteed to be correct")

19.2 abnormal transmission

def demo1():
    return int(input("Please enter an integer:"))


def demo2():
    return demo1()

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

19.3. Actively throw exception

def input_password():

    # 1. Prompt the user to enter the password
    pwd = input("Please input a password:")

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

    # 3. The password is not long enough and an exception needs to be thrown
    # 1> Create exception object - use the exception's error message string as a parameter
    ex = Exception("The password is not long enough")

    # 2> Throw exception object
    raise ex
    
try:
    user_pwd = input_password()
    print(user_pwd)
except Exception as result:
    print("Errors found:%s" % result)

Topics: Python