1, Foundation
1. Language related issues
- Q: what are the characteristics and advantages of python?
Features: python is an interpretive language. The code is interpreted and executed through the interpreter. The code that is executed is interpreted. There is no need to precompile to generate executable files.
Disadvantages of interpretive language: it relies too much on the interpreter environment. The interpreter is a virtual environment. Before running the code, you have to apply for memory, open up space, start the interpreter and consume more memory.
python disadvantages: low execution efficiency
Advantages of Python: high code writing efficiency, fast development speed and good cross platform (one-time development, running everywhere, as long as there is a python parser on Window, Linux and Mac, you can run Python code). It is relatively easy to learn and there are many open source projects.
- Q: why do you use python for development and how did you get started with python development?
You can list the reasons: you learned python in college, and you learned python in your internship. You find python very interesting: say the advantages of the previous question...
- Q: what language have you used when you came out of python?
JavaScript (must know, web page scripting language, and JS language is used in vue)
- Q: what is a compiled language
Compiled languages need to be compiled first to generate a binary file, such as C, and generate an exe executable file; Then it's executing.
Advantages: high execution efficiency.
Disadvantages: debugging bugs is troublesome, and the process of writing code is slow to produce results (the effect cannot be seen immediately after writing code, so it needs to be compiled and executed first)
2. python PEP8 specification
PEP8 specification is the guiding specification for python code writing. It is not a syntax error, but a writing specification. (if it is not observed, the code will not report an error)
Indent each line with 4 spaces
The maximum number of characters for all lines is 79
It is not recommended to import multiple modules in one row (one module in one row)
It is easy to make mistakes without using single character as variable name (1 and 0 are like I and O)
Class names should be capitalized; Function names should be lowercase. If you want to improve readability, you can separate them with underscores.
3. What are the common codes
ASCII 1 byte English language (0-9 a-z A-Z characters)
GBK 2-byte Chinese code supports traditional characters
UTF-8 variable length code (1-3 bytes) universal code supports various languages
1. In order to process English characters, ASCII code is generated.
2. In order to process Chinese characters, GB2312 is generated.
3. In order to process national characters, Unicode is generated.
4. In order to improve the storage and transmission performance of Unicode, UTF-8 is produced, which is an implementation form of Unicode
2, python Foundation
1. The difference between p2 and p3
1, python2 use print Print python3 use print()Method printing 2,python2 The result of division is an integer python3 The result of division is floating-point data, and the double slash is required for integer division// 3,python2 Default is ASCII Code to use unicode Need special definition unicode String example u'hello' python3 Default is unicode(utf-8)character string 4,p2 The advanced function returns list p3 Returned by advanced function iteration iterator
2. is and = = difference
==True as long as the values are the same
is requires not only the same value, but also the same address to be True
For example, if x = 1 and y = 1, x is y is True. This is because there is a constant pool in python, 1 belongs to the constant pool, and X and Y refer to the same constant, so their addresses are the same.
For example, x=[1,2,3] y=[1,2,3] x==y is True, but x is y is False because X and y are different memory spaces and address pages are different
[the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (IMG njsfrtef-1619739993112) (... /... /... / images/image-20210427105228602.png)]
3.range and xrange
I haven't used xrange. I've used range. Range represents a range, and the range function returns an iteratable object), not a list type. The range function in Python 2 returns a list.
range(1,5) does not include 5. Generally, the parameters of this interval in python are greater than or equal to the latest value and less than the maximum value
According to my investigation, when Python 3 returns the list, it returns the iteratable object instead of directly returning the list.
4. Ternary expression
true expression if judgment expression else false expression
y= 20 if x==3 else 10
5. Interchange variables
x,y=3,4 x,y=y,x Can be achieved x And y The exchange of values by x=3 y=4 Instead x=4 y=3 Sequence unpacking sequence packet
6. Deep copy and shallow copy
-
Shallow copy: only the first layer is copied, and no deep layer is copied. Modifying the first layer does not affect each other. Modifying the second layer affects each other.
-
Deep copy: a recursive copy will generate a set of exactly the same content in memory, and the modification will not affect each other
Slicing is a shallow copy.
x = ["1", "2", ['a', 'b', 'c'], "3", "4", "5"] y = x[:3] print(id(x), id(y)) y[2].append('k') print(x, y)
7. Introspection of python
When the program is running, it can get the information of the object, 3 properties and 2 types
Introspective attribute | introduce | use |
---|---|---|
dir | Get all properties in the object (properties and methods; properties and methods inherited from the parent class) | |
type | View the type of object | |
hasattr | Determine whether there is an attribute in the object | |
getattr | Get the property value of the object according to the property name | |
isinstance | Determine whether the object is a type | |
Case:
class Student: country = "China" def __init__(self, name, age=None): self.name = name self.age = age def say(self): print("I am{}") return "OK" def add(): print("add") if __name__ == '__main__': s = Student("Zhang San") print(dir(s)) # print(type(s)) print(hasattr(s, "gender")) print(getattr(s, "name")) print(getattr(s, "say")()) print(isinstance(s, list)) print(isinstance(s, Student))
8. CSV file, what is it
Comma separated values (CSV, sometimes referred to as character separated values, because the separating character can also be not a comma), and its file stores tabular data (numbers and text) in plain text
Simply put: store table type data in plain text
#test.csv full name,Age,occupation,Native place,wages Cao Cao,33,student,Henan,8000 Liu Bei,53,student,Sichuan,5000 Sun Quan,23,student,Jiangsu,6000
Our python provides a csv module, which can realize the operation of csv
import csv def writeTO(): with open("D:\\test.csv", 'w', newline='') as f: rowh = ["full name", "Age", "occupation", "Native place", "wages"] row1 = ['Cao Cao', '33', 'student', 'Henan', '8000'] row2 = ['Liu Bei', '53', 'student', 'Sichuan', '5000'] row3 = ['Sun Quan', '23', 'student', 'Jiangsu', '6000'] write = csv.writer(f) write.writerow(rowh) write.writerow(row1) write.writerow(row2) write.writerow(row3) print("Write complete!") def readCVS(): with open("D:\\test.csv", 'r') as f: r = csv.reader(f) row_header = next(r) print(row_header) for row in r: print(row) # Print effect ['full name', 'Age', 'occupation', 'Native place', 'wages'] ['Cao Cao', '33', 'student', 'Henan', '8000'] ['Liu Bei', '53', 'student', 'Sichuan', '5000'] ['Sun Quan', '23', 'student', 'Jiangsu', '6000']
9. What compression types are available
tar: knowledge packs multiple files together, not a compressed format.
zip: the most common compression format, which is relatively fast.
rar: the file compression ratio is higher than zip, but the compression speed is slow and the random access speed is slow.
10. Persistence
Talk about the persistence of transient data (data in memory) into persistent data (stored in files and databases)
JSON module is to persist the JSON format, using JSON Load (FP)
11. Parameters
12. Recursion
– handwritten code
Recursively write Fibonacci sequence, factorial, variable file directory
Fibonacci sequence 1 1 2 3 5 8 13 21 f(n-2)+f(n-1)=f(n) """ def f(n): if n == 1 or n == 2: return 1 return f(n - 1) + f(n - 2) for i in range(1, 10): print(f(i), end=" ")
''' Recursive traversal of file directory ''' path = "E:\\Cumulus education materials\\2021 Annual data" import os # The interface between python and sys is provided by the underlying parser def fileRead(path, level=1): for file in os.listdir(path): # listdir(path) gets all the files (files, directories) in this directory # Print all files and subdirectories of a directory print("%d%s%s" % (level, level * '-', file)) # If this is a directory if os.path.isdir(os.path.join(path, file)): # Then recursively call to traverse the subdirectory fileRead(os.path.join(path, file), level + 1) fileRead(path)
14. Regular
- Matching pattern
1,Greedy model By default, regular expression search tends to the maximum matching. As many matching characters as possible is the greedy pattern 2,Non greedy model Regular expressions match as few characters as possible when searching. Use question marks? After the number of matching characters is reached, the non greedy mode is realized case: *? *The number is matched by the least matching mechanism, that is, 0 times (* Indicates that the subexpression appears 0 or more times, which can be 0 times) +? +The least matching mechanism of the number, that is, once(+ Indicates that the subexpression occurs one or more times, at least once)
- Match times metacharacter
{m,n} Specify the number of matches m reach n second {m} Matching times greater than or equal to m second ? The number of matches is 0 or 1 + The number of matches is 1 or more * The number of matches is 0 or more
- Common regularization methods
re.match Match a string that conforms to the rule from the beginning, starting from the starting position An object is returned when matching is successful, but not successfully None re.search The function looks for a pattern match within the string, starting anywhere in the string Returns if the string does not match None
15. random module
python in random The module is used to produce random numbers random.random Used to produce a random floating-point number from 0 to 1: random.randomint(a,b) Used to produce one[a,b] Integer in range random.choice(seq) Used to randomly select an element from a sequence random.shuffle(list) Used to disrupt elements in a list # This is to modify the list itself. If you disturb its order, it must be modifiable. Therefore, you can't disturb the order with strings and tuples. You can only modify the list
16. json module
import json dic = {"name": "Tom", "age": 22, "gender": "male"} s = json.dumps(dic, ensure_ascii=False) print(s,type(s)) r=json.loads(s) print(r,type(r))
17. Partial function
Partial function can fix the parameters of the function, which is convenient to use and call
"""Partial function""" import functools def add(x, y, z): print(x, y, z) return x + y + z add1 = functools.partial(add, 10) print(add1(20, 30)) print(add1(15, 60)) add2 = functools.partial(add1, 20) print(add2(100))
2, Object oriented
1. Object oriented understanding
Encapsulation:
Succession:
Polymorphism:
2. Multiple inheritance
MRO Continue search order Used to determine the order in the case of multiple inheritance python3 Breadth first algorithm
3. And super self
super is a method that can get the parent class in the subclass. super can also be used to actively solve multiple inheritance problems
Self is used to point to the current instance. In the class, the attribute pointed to by the self pointer is an instance attribute, which can only be accessed by the instance
When an instance calls a method, the first parameter self of the instance method will be automatically passed into the current instance,
4. Main magic methods
__new__ __init__ __call__ __del__
5. Method, class, method attribute
6. Metaclass
Singleton mode
7. Algorithm
7.1 binary search
Binary search, also known as half search algorithm,
Simple binary search takes little time, and its spatial complexity is O(1) and time complexity is O(logN)
Note: dichotomy search is a quick search for ordered data sets
# Dichotomy search -- circular search def find_while(list, val): left = 0 right = len(list) - 1 while True: if left > right: return -1 middle = (left + right) // 2 print("left:{} right:{} middle:{}".format(left, right, middle)) if list[middle] == val: return middle elif list[middle] < val: left = middle + 1 else: right = middle - 1 # Dichotomy search -- recursive search def find_digui(list, val, left, right): if left > right: return -1 middle = (left + right) // 2 print("left:{} right:{} middle:{}".format(left, right, middle)) if list[middle] == val: return middle elif list[middle] < val: left = middle + 1 else: right = middle - 1 return find_digui(list, val, left, right)
8. Common mode
8.1. Handwriting single example mode
class Student: __instance = None # Judge__ Whether the instance property is None def __new__(cls, *args, **kwargs): if cls.__instance is None: cls.__instance = super(Student, cls).__new__(cls, *args, **kwargs) return cls.__instance else: return cls.__instance if __name__ == '__main__': stu = Student() stu1 = Student() stu2 = Student() print(id(stu), id(stu1), id(stu2))
9. Monkey patch
The main function of monkey patch is to add and change the functions without changing the source code. It is particularly useful when some third parties are not satisfied in the programming process
Is a programming skill.
class Student: age = 30 def run(self): print("Run fast, run fast") def new_run(*args): print("Who am I?,who are you!") def hello(*args): print("hello everyone!") if __name__ == '__main__': stu = Student() stu.run = new_run stu.hello = hello stu.run() stu.hello()
10. Iterators and iteratable objects
have __iter__ __next__ The object of the magic method becomes an iterator Iteratable objects are also implemented__iter__Method, not necessarily implemented__next__ Iteratable objects are supported for Cyclic iteration Lists, tuples, strings, and dictionaries are all iteratable objects
Functions that can produce iterators (iterator generator)
count(start,step) produces infinite return iterators
import itertools import time iter1 = itertools.count(1, 2) for i in iter1: print(i) time.sleep(2) 1 3 5 7 9
Obj iterator
iter2 = itertools.repeat([1, 2, 3]) for i in iter2: print(i) time.sleep(2) [1, 2, 3] [1, 2, 3] [1, 2, 3] [1, 2, 3] [1, 2, 3]
3, Threads and processes
1. Thread, process
2. Synergetic process
3. yield implementation process
4. Lock and semaphore
5. GIL lock
4, Network foundation
1. C/S and B/S architecture
2. OSI layer 7 and TCP layer 4
3. TCP heartbeat packet
4. Multiplex IO
5. Blocking and non blocking
6,select,poll,epoll
5, Advanced programming
1. Reflection
2. Monkey patch
3. Iterator
4. Generator
5. Design mode
5, Algorithm
1. Binary search
2. Select sort
3. Bubble sorting
4. Quick sort
itertools
import time
iter1 = itertools.count(1, 2)
for i in iter1:
print(i)
time.sleep(2)
1 3 5 7 9
repeat(obj) Production repeat iterator
iter2 = itertools.repeat([1, 2, 3])
for i in iter2:
print(i)
time.sleep(2)
[1, 2, 3] [1, 2, 3] [1, 2, 3] [1, 2, 3] [1, 2, 3]
## 3, Threads and processes ### 1. Thread, process ### 2. Synergetic process ### 3. yield implementation process ### 4. Lock and semaphore ### 5. GIL lock ## 4, Network foundation ### 1. C/S and B/S architecture ### 2. OSI layer 7 and TCP layer 4 ### 3. TCP heartbeat packet ### 4. Multiplex IO ### 5. Blocking and non blocking ### 6,select,poll,epoll ## 5, Advanced programming ### 1. Reflection ### 2. Monkey patch ### 3. Iterator ### 4. Generator ### 5. Design mode ## 5, Algorithm ### 1. Binary search ### 2. Select sort ### 3. Bubble sorting ### 4. Quick sort