Day10 python scope Python2.7 and python3.x class inheritance differences and other

Source: Internet
Author: User

One, Python scope

1. No block-level scope in Python

if 1 = =1    :'test'print(name)#  The output will error because the scope of name is limited to the code block under if and not to the global

2. Use function as scope in Python

def func ():     ' func_test ' Print (Func_name) # This will also cause an error, because the variable func_name function in the Func function

3, Python scope chain, layer nesting, use from inside outside to look for

4. The scope of Python has been determined before execution

' Test ' def F1 ():     Print (name) def F2 ():     ' f2_test '    return  = F2 () res ()# Final output result is test

eg

Li = [lambda for in range]#  print (LI)print(Li[0] ( )   # output is 9"' lambda:x for X" inRange (10) will decompose above lambda:x =:d ef func ():    return XX for x in range x equals 0-9x for x in range (10) is a block of code, so x is a global variable lambda:x a function, the value of x is not defined in the function, so x takes the value of x in the global variable, At the end of the For loop, the last value of X is 9, so the value of x in LAMDBA is 9"

The difference of class inheritance between Python2.7 and python3.x

code example:

classA (object):defF1 (self):Print('A')classB (A):defF2 (self):Print('B')classC (A):defF1 (self):Print('C')classD (B):defF2 (self):Print('D')classE (C):defF1 (self):Print('E')classF (d,e):defF2 (self):Print('F') obj=F () obj.f1 ()

The following is the difference between the class inheritance of the above code in Python2.7 and python3.x

Python2.7 (the class that does not inherit object by default is called a classic class, and the class that inherits object by default is called a modern class, and Python3 inherits object by default, so there is no difference between a new class and a classic class in Python3)

When looking for a method, look for the following order (first left and right)

python3.x

Third, IO asynchronous

io multiplexing    overview        select,poll,epoll    Listen to the inside of the socket object is it changing?    when does it change? Connect or send and    receive messages -"There's a new connection coming    ... SK: There's a new connection coming    ... Conn: To receive the "Hair" message     --listen to the inside of the socket object is changed?    

Using Select to implement IO Async

#!/usr/bin/env python#-*-coding:utf-8-*-#Author:alex LiImportSocketImportSelectsk=socket.socket () Sk.bind ('127.0.0.1', 9999,)) Sk.listen (5) Inputs=[Sk,]outputs=[]messages= {}#del messages[Baiyu]#messages = {#Baiyu: [MSG 1, MSG 2,]#Wu Wenyu: [MSG 1, MSG 2,]# } whileTrue:rlist,wlist,elist,= Select.select (Inputs, outputs,[sk,],1)    Print(len (inputs), Len (rlist), Len (wlist), Len (outputs))#listen to the SK (server side) object, if the SK object changes, indicating that there is a client to connect, at this time the rlist value is "SK"    #listen to the Conn object, if the conn changes, indicating that the client has a new message sent over, at this time rlist "client"    #rlist = "Wu Wenyu,"    #rlist = "Zhang Lei, Baiyu,"    #rlist = [SK,]     forRinchrlist:ifr = =SK:#new customers to connectConn, address =r.accept ()#what is conn? In fact, the socket objectinputs.append (conn) Messages[conn]=[] Conn.sendall (Bytes ('Hello', encoding='Utf-8'))        Else:            #someone sent me a message.            Print('=======')            Try: Ret= R.RECV (1024)                #R.sendall (ret)                if  notret:RaiseException ('Disconnect Connection')                Else: Outputs.append (R) messages[r].append (ret)exceptException as E:inputs.remove (r)delMessages[r]#all the people who sent me a message.#实现读写分离
     for inch wlist:         = Messages[w].pop ()        = msg + bytes ('response', encoding=' Utf-8 ' )        W.sendall (resp)        Outputs.remove (w)#  rlist = [sk,],rlist=[sk1,],rlist = [Sk1], SK2]#  rlist = []

Four, multi-threaded (threading module)

Import  Time def F1 (i):    time.sleep (1)    print(i)import  threading  for  in range:    = Threading. Thread (TARGET=F1, args=(J,))    T1.start ()# The final output is not output in 0-9 order, T1.start () is random
Import TimedefF1 (ARG, t=None):ifT:t._delete () time.sleep (5)    Print(ARG)#For I in Range (Ten):#F1 (i)#single-process, single-threaded applicationImportTHREADINGT1= Threading. Thread (TARGET=F1, args= (1,))#T.setdaemon (True) # True, which indicates that the main thread is not equal to this child threadT1.start ()#does not mean that the current thread will be executed immediately#T.join (2) # indicates the main thread to this, waiting ... Until the child thread finishes executing                   #parameter, which indicates that the main thread waits at most n seconds hereT2= Threading. Thread (Target=f1, args= (2, T1)) T2.start ()#does not mean that the current thread will be executed immediatelyPrint('End')Print('End')Print('End')Print('End')Print('End')

Five, multi-threaded, multi-process

Overview:     1, an application, can have multi-process and    multi-threaded 2, default: Single process    , single thread 3, single process, multi-threaded: IO operation, do not consume CPU        IO operation, do not occupy CPU            Multithreading improves concurrency        computational operations, consumes CPU            multi-process increase concurrency     4, GIL, global interpreter lock     = = ="        multi-threaded, multi-process  provider concurrency        IO-intensive: multithreaded        COMPUTE intensive: Multi-process           Ps:io operation, no CPU     GIL, global interpreter lock

Day10 python scope Python2.7 and python3.x class inheritance differences and other

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.