Python Full Stack Development Note 4

Source: Internet
Author: User

Reflection

1. Importing modules as strings

2. In the form of a string, go to the module to find the specified function and execute

" "def f1 (): Return ' F1 ' def f2 (): Return ' F2 '" "#Let's say the above is the contents of a py file called user.#Import User # User is not a string, is a file name and cannot be imported as a stringdo=__import__('User')#by importing the module as a string, ' user ' is a string that implements the first function of reflection. R=do.f1 ()Print(r)#Output F1R=getattr (Do,'F1')#A function named F1 is found in the module do, and the F1 in parentheses is a string that returns the address of the F1 function.Print(R ())#output F1, by executing the function with parentheses after R, R is a function address, which implements the second function of reflection. #hasattr to determine if a function in the form of a string exists in the module#setattr (Do, ' age ', 8) set a global variable for a module#setattr (Does, ' age ', lambda a:a+1) sets a function for a module, followed by a lambda expression#delattr Delete a function or variable in a module#Summary: Reflection is the act of manipulating its members into objects (a module) in the form of a string, which is one of the objects. 
Object oriented

If a function is written in a class, it is called a method, and the class name is appended with parentheses to create an object, and object-oriented is not applicable in all cases.

Self is a formal parameter, Python internally passed, Obj=foo () creates an instance of obj as Foo, obj.fetch (' BB '), invokes the Fetch method in Foo, this process defaults to Self=obj, is an address, The __init__ method in the class is executed first when the object is created, and he has a special method called the constructor method.

The __DEL__ interpreter automatically invokes the object when it is destroyed, with a special name: the destructor method.

Encapsulation: Using scenarios, when the same type of method has the same parameters, directly encapsulated in the object, the class as a template to create multiple objects (the data within the encapsulated object can be different)

Inheritance: Both derived and base classes have precedence in the derived class, and Python classes can inherit multiple classes at the same time, first themselves, and then from left to right.

Polymorphic: Multiple forms, Python language features natively support polymorphism, extension: overloaded (the function name is the same, the number of arguments is not the same, Python does not support, override: A method of re-implementing a base class in a derived class. )

The process of finding the source code (self. XXXX (), starting from the bottom of the search)

Performs how the parent class is constructed: Super (current class, self). Init () Parent class. __INIT__ (SELF,XXX)

Fast judgment of class execution and object execution, self, object invocation, no self, class invocation.

classProvice:country=' China'#static field exists in class    def __init__(self,name): self. Name=name#name exists in object@property#attribute, plus this, means creating an attribute that forges a method into a field    #the attribute method can no longer pass any parameters, except self, which is used to obtain    defEnd (self): temp='%s End'%Self . NamePrint(temp) @end. Setter#indicates that the value can be set to end, passed to value, and printed to be set, but end must have the same name as the above attribute.     defEnd (Self,value):Print(value)defStart (self): temp='%s Start'%Self . NamePrint(temp)defShow (self):#ordinary methods exist in the class, but ordinary objects can be called by pointers        Print('Output Place')        Print(self.) Name,provice.country)#use class when accessing static fields. Static field access, if yes        #object to its own members, then use its own to access the object itself. The members, except the methods in the class. @classmethod#class Method    defXxoo (CLS):#The class method must have a CLS parameter, full name class, accessed through the class, and the parameter is the class name of the current class        Print('Xxoo')        Print(CLS) @staticmethod#just use this one decoration, the following method will become static method, no self    #static methods belong to the class, when executed, with the class name plus method, without arguments, the object can also be accessed, but the recommended class for access.     defXo ():#it can have any arguments, but it takes one by one to pass it when called, but it doesn't need self anymore.         Print('XO')     #the normal method must first create the object, but the static method does not need to create the object to be executed directly. Henan=provice ('Henan') Henan.show () Provice.xxoo () RET=provice ('HAHA') Ret.start () Ret.end#calling an attribute method does not need to be in parentheses to get. Ret.end='Shallow'#to execute the End function with the @end. Setter, which can be used to modify. 
Member modifiers

The front add __ (two underline), then can not get outside, only within the class access, in the subclass also cannot access, but through indirect access, through the method. Nothing is public and can be accessed outside.

Parentheses after an object execute the __call__ method. The equivalent of two parentheses foo () () after the class executes the __call__ method. The __getitem__ method is executed after the object is added []. Object. __dict__ gets all the fields in the object. __doc__ annotation, print (object) can output the result directly because the __str__ method in the class is executed.

Assertions are typically used for testing

Single-Case mode

When the data encapsulated in all instances is the same, the singleton mode

#Single-instance mode----classConnectionPool:__instance=Falsedef __init__(self):#What you need to create a connection poolself.ip='1.1.1.1'Self.port=3306self.pwd='123123'Self.username='xxxx'self.conn_list=[1,2,3,4,5,6,7,8,9,10]#Create 10 chain connections@staticmethoddefget_instance ():ifConnectionPool.__instance:            #if it was previously created, it is returned to the previous one and will not be recreated            returnConnectionPool.__instance        Else:            #creates an object and assigns the object to a static field __instanceConnectionPool.__instance=ConnectionPool ()returnConnectionPool.__instance            defget_connection (self):#Get Connections        ImportRandom R=random.randrange (1,11)#random access to a chain connection        returnR pool1=connectionpool.get_instance () pool2=connectionpool.get_instance ()Print(pool1,pool2)#The output is the same as the address, the description is just an object, avoids duplicate creation, singleton mode#<__main__. ConnectionPool object at 0x000001ee554c9198> <__main__. ConnectionPool object at 0x000001ee554c9198>
Network programming

Socket based on TCP, IP (socket) client service side, all clients to connect to the server, the server first run, IP, port (ports) waiting for others to link

Socketserver concurrent processing of multiple client requests, using: 1, creating classes, must inherit 2, handle Method 3, Server_forever

Process

Pros: Take advantage of the multi-core advantage of the computer (capable of multiple operations at the same time) disadvantage: Wasting the computer's resource memory (re-opening the memory space), the process is not the more the better, the number of CPUs = number of processes the best.

Thread

Advantage: Shared memory, IO operations can create concurrent operations. Disadvantage: The preemption of resources, the number of threads is not the better, concrete case specific analysis, request context switching time consuming.

Process and threading Purpose: Improve execution efficiency.

The smallest unit of execution of a task in a computer is a thread. IO operations do not take advantage of Cpu,io intensive multi-threading, computationally intensive needs with multi-process

GIL Global Interpreter Lock

ImportThreadingImport Timedeffunc1 ():Print('111')defFunc2 (A1,A2): Time.sleep (1) func1 ()Print('a1+a2=%d'% (a1+A2)) T1=threading. Thread (target=func2,args= (123,111,))#args passed in a tuple, creating a sub-thread#A child thread is created by the main thread, which executes from the top, and when this line of code is encountered, a child thread is createdT1.setdaemon (True)#After you set the main thread to wait for the child thread, the default is waiting, changing to true will not wait, if you do not wait, the main thread will#Execution finishes after creating the following three sub-threads, and does not wait for the child thread to execute the FUNC2 functionT1.start ()#let the created thread start executing#T1.join () #让这个线程不再并发执行, wait until the thread finishes executing, and then execute the following, which will indicate a maximum of a few seconds when the parameter is passed inT1.join (2)#The following code waits at most this thread for 2 seconds, and if it does not finish, it will continue to do the following, if the thread does not finish, it will continue to execute in the background, but will not wait for himT2=threading. Thread (target=func2,args= (123,111,))#args passed in a tuple, creating a sub-threadT2.start ()#let the created thread start executingT3=threading. Thread (target=func2,args= (123,111,))#args passed in a tuple, creating a sub-threadT3.start ()#let the created thread start executing
Thread Lock

Python does not provide a thread pool internally, requires custom data sharing M=manger () dic=m.dict (), and process pool Python has provided

Context Management
#the With open (XX) as SS principle is implemented with context management. ImportContextlib@contextlib.contextmanager#for context ManagementdefMyopen (File_path,mode): F=open (file_path,mode,encoding='Utf-8')    Try:        yieldF#performing this step will take F out and assign it to the object behind the AS.    finally: F.close () with Myopen ('XXX.txt','R') as File_obj:Print(File_obj.readline ())#Executes the task, and then executes the contents of the finally after all tasks are completed
Css

1. First find the label, 2. Work with that tag

Python Full Stack Development Note 4

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.