Summary of Dark Horse programmers 2-python advanced programming, 2-python Advanced Programming
10 tips for Python Development
Exam
def extendList(val,list=[]): list.append(val) return listlist1=extendList(10)list2=extendList(123,['a','b','c'])list3=extendList('a')print(list1)print(list2)print(list3)
[10, 'a']['a', 'b', 'c', 123][10, 'a']
The list2 parameter is initialized and passed in.
List1 and list3list2 are called without parameters. The default list initialized by extentdList is used (the address is the same and the list is variable). Therefore, 10 and a are added to the list twice, respectively, get [10, 'a'].
The list addresses returned to list1 and list3 are initialized by extendList, so the returned values are the same.
A. import math
Sometimes we only need to use a function in the module. We only need to introduce this function. At this time, we can use the following method to implement it:
B. from Module name import function name 1, function name 2 ....
C. from modname import name1 [, name2 [,... nameN]
From fib import maid
Note:
Instead of importing the entire fib module into the current namespace, it will only introduce a single fiber ACCI in fib
D. It is also feasible to import all the content of a module to the current namespace. You only need to use the following statement:
From modname import *
This provides a simple way to import all projects in a module. However, such declarations should not be used too much.
E.
Import time as tt
Each Python file can be used as a module. The module name is the file name.
For example, a file named test. py defines the function add in test. py.
Test. py
Def add (a, B ):
Return a + B
In other files, you can import test first, and then use test. add (a, B) to call it. Of course, you can also use from test import add to introduce
Main. py
Import test
Result = test. add (11,22)
Print (result)
You can determine whether the python script is directly executed or introduced for execution based on the result of the Variable _ name _, so as to selectively execute the test code.
A package organizes associated modules into the same folder and creates a file named _ init _. py in this folder. This folder is called a package.
What is the use of the _ init _. py file?
_ Init _. py controls the package import Behavior
2.1 _ init _. py is empty
Only import this package, not the modules in the package
Local module Installation Method
Find the compressed package of the module
Extract
Go to the folder
Run python setup. py install
The list derivation refers to the lightweight cycle creation list.
Set, list, And tuple can be converted to each other.
You can use set to quickly deduplicate the elements in the list.
Interview
Class A (object ):
Def foo (self, x ):
Print ('foo (% s, % s) '% (self, x ))
@ Classmethod
Def class_foo (self, x ):
Print ('foo (% s, % s) '% (self, x ))
@ Staticmethod
Def static_foo (x ):
Print ('foo (% s) '% x ))
A = ()
A. foo (1)
Print ()
A. class_foo (1)
A. static_foo (1)
Foo (<__ main _. A object at 0x7f3adbdf37b8>, 1)
<__ Main _. A object at 0x7f3adbdf37b8>
Foo (<class '_ main _. A'>, 1)
Foo (1)
Python core programming
L = [ x*2 for x in range(5)]
Generator features:
- Memory saving
- During iteration to the next call, all the parameters used are reserved for the first time, that is, they are retained when all function call parameters are called for the first time, rather than newly created
- All objects that can act on the for loop are of the Iterable type;
- All objects that can act on the next () function are of the Iterator type.
- Set data types such as list, dict, and str are Iterable but not Iterator. However, you can use the iter () function to obtain an Iterator object.
An example of a closure:
def line_conf(a, b): def line(x): return a*x + b return lineline1 = line_conf(1, 1)line2 = line_conf(4, 5)print(line1(5))print(line2(5))
Closures can also improve code reusability.
Module modification, reload to be reloaded
Avoid repeated import, egg and egg
- Is to compare whether two references point to the same object (reference comparison ).
- = Is to compare whether two objects are equal.
Shallow copy: copy reference, no copy content, address given, pointing to the same address.
Deep copy: Copies all layers of an object using the copy. deepcopy module. Copy content to new memory.
The list copy function is variable and the new memory is used. The ancestor is immutable. copy () points to the same location (memory ).
Garbage Collection
- Small integer [-5,257) shared object, resident memory
- Shared object for a single character, resident memory
- A single word cannot be modified. The intern mechanism is enabled by default. The shared object is destroyed if the reference count is 0.
Closure: first, call the external parameter, and then pass the parameter to call the internal function. Used to prevent repeated variables. Simplify calling. Optimization variable.
Def foo ():
Print ('foo ')
Foo # indicates a function.
Foo () # indicates executing the foo Function
Def foo ():
Print ('foo ')
Foo = lambda x: x + 1
Foo () # execute the following lambda expression instead of the original foo function, because the name of foo is overwritten by the lambda anonymous function.
The decorator is automatically executed when it arrives, and the function closure is called.
System Programming
Process thread
Process to complete multiple tasks, such as running multiple QQ
Thread to complete multiple tasks, such as multiple chat windows in a QQ
There are two implementation methods
Multi-task, time slice rotation, priority call. Concurrency: supports multi-task processing, not necessarily at the same time. Parallel Processing: multi-task processing at the same time.
The return value of fork is special. Multiple processes are generated. Fork () is called once, returns twice, and returns 2.
The child process always returns 0, and the parent process returns the child process ID ., The parent process is greater than 0;
In multiple processes, all data (including global variables) in each process has one copy, which does not affect each other.
Multi-process alignment. If the multi-process conforms to n of 2, each of them must fork once.
There are many server processes. pid IDs are similar to ID cards. They are different from multiple processes. All data (including global variables) in each process have one copy, which does not affect each other, the execution sequence of parent and child processes is not regular, and it depends entirely on the scheduling algorithm of the operating system. Total process: 2 * n times, generally no more than 8 times.
The multiprocessing module provides a Process class to represent a Process object. Sub-processes can be implemented using classes.
While true
Super multi-task, Pool process Pool cache apply Blocking
Multi-threaded concurrent operations are used, saving time and irrelevant execution sequence.
The thread shares global variables, making data sharing easy, and passing parameters in the list also sharing. Process cannot (Process Communication is initiated)
Create a folder for the OS module, debug OS. mkdir (), and print
Queue can be used to solve the percentage Problem
Thread:
Multi-threaded concurrent operations take much shorter time
To start a created thread, you must call the start () method.
Thread created and executed together
In multi-thread development, global variables are data shared by multiple threads, while local variables are of their respective threads and are not shared.
Synchronization (locking, regular): synchronization is a collaborative pace that runs in a predetermined order. For example, if you have finished speaking, I will talk about it again. For example, process and thread synchronization can be understood as A combination of process or thread A and thread B. When A executes to A certain extent, it depends on A result of B, so it stops and signals B to run; b. Execute the statement, and then send the result to A; A. Continue the operation.
Asynchronous: No conventions
Synchronous call means that you call your friend for dinner, your friend is busy, and you are waiting there all the time. When your friend is busy, you can go together.
Asynchronous calling means that you call your friend for dinner. Your friend says you know, and you will do something else when you are busy looking for you.
Reconstruction: rewrite
Although a ThreadLocal variable is a global variable, each thread can only read and write independent copies of its own thread without interfering with each other. ThreadLocal solves the problem of parameter passing between functions in a thread.
Be especially careful with global variables in multiple threads; otherwise, data disorder may occur.
Network Programming
TCP/IP protocol family, layer-4 reality
Port, marking processes (using pid on the same computer), communication between different computers
IP address 127.0.0.1 ~ 127.109255 cannot be used for loop test network number + multicast number (multicasting, some cannot be viewed, video conferencing)
All connected devices have ip addresses.
With the IP address and protocol, the port can identify the network process, and the process Communication in the network can use this flag to interact with other processes.
Socket ip + port + Protocol
As few code as possible, saving
TFTP client
Download: Create File-write data-close
Upload:
Cisco packet
Mask: the binary mask and ip address are bitwise AND obtained to obtain the network number (Class c's last bits 255.255.255.0). The three 255 bits represent the network number, and the 0 bits represent the host number.
The network cable can only be connected to two computers (multiple data and electrical signals in the network are disordered), and multiple switches eliminate the Hub (USB expansion)
A Router, also known as a Gateway, is used to connect multiple logically separated networks.
NIC: physical address, actual address
Default Gateway:
For a pc that is not in the same CIDR block, you must set a default gateway to transmit data. Generally
Hub: broadcast, switch: more intelligent
Tcp stipulates that cross-network communication is not allowed. The dual-ip address of the router Nic and the right hand can be connected to different network segments,
The IP address communication will not change, and the mac address will change.
Ping TTL = 128, after a router minus one
Cdn distribution, server placement in various regions
Arp third-party fraud
Nat: ip Intranet and Internet performance, route table address translation, can only be mapped to the external, your own server cannot access the Internet, with the help of peanut shells.
-
Top
-
0
-
Step on
-
0
View comments