Python Learning Summary (function advanced)

Source: Internet
Author: User
Tags closure

-------------------program operation principle-------------------1, the module built-in __name__ property, The main module value is __main__, Import module value is module name     1, creation time, PY file is newer than the PYC file, the PYC is newly generated.     2, Magic num, do the Pre-run version test, the version is different to regenerate pyc.     3, pycodeobject object, string in source code, constant value, bytecode instruction, corresponding relation of original code line Number.  2, LEGB rules     1, local         current namespaces (such as functions, modules), function parameters also belong to variables within the Namespace.     2, ecolsing function: namespaces for external nested functions         namespaces for outer nested functions (common in closures).     3, global: globally         Global variables, The function defines the namespace of the module in which it Resides.     4, builtins: built-in module namespace         1, Python will automatically load many built-in functions, classes, such as dict,list,type,print, when it is Started. These are located in the __builtins__ module and can be viewed using dir (__builtins__).         2, in python, there is a built-in module that has some common functions, and Python loads the built-in function into memory before Python starts and does not execute any code written by the Programmer. In addition, the functions in the built-in module can be used directly, without adding the built-in module prefixes before them, because the search for identifiers such as functions, variables, and classes is based on the LEGB rule, where B represents the built-in Module.  3, dir functions     Python's built-in functions dir can be used to view all the name symbols under a namespace. One use is to look at all the properties and methods of a namespace (the namespace here refers to a class, function, module).  4, garbage collection     1, small integer object Pool: &nbsp       1, integers are used extensively in programs, and Python uses a small integer pool of objects to optimize speed, avoiding the frequent application and destruction of memory space for Integers.         2, Python defines small integers as [-5, 257] These integer objects are set up well in advance and are not garbage collected. In a Python program, all integers that are in this range use the same object.     2, Large integer object Pool: creates a new object for each large integer.     3, intern mechanism:        Python has such a mechanism--intern mechanism, so that he occupies only a "HelloWorld" of memory space. By reference counting to maintain when to Release.  5, Summary     1, small integer [-5,257] common objects, resident Memory.     2, single character shared object, resident Memory.     3, single word, non-modifiable, default on intern mechanism, Common object, Reference count is 0, then Destroy.     4, string (containing spaces), can not be modified, did not open the intern mechanism, not the common object, the reference count is 0, Destroyed.     5, large integers do not share memory, reference count is 0, destroy.     6, note: numeric types and string types are immutable in Python, which means that you cannot modify the value of this object, and each time you modify a variable, you are actually creating a new Object.  6, def command     1, def func (), is make_function in the bytecode Directive. Python is a dynamic language, and DEF is actually executing an instruction to create a function (class is the instruction to create it), not just a syntax Keyword. The function is not created in advance, but only when it is Executed.     2, def func () will create a function object called Func. is actually to create a function object first, and then bind the Func name symbol to this Function.  7, Import Search path when importing packages:    1, path search:        Import Sys&nbsP       Sys.path: View the path of the import package     2, Import the module path at program execution         Sys.path.append ('/home/usr/ Local/images ')         Sys.path.insert (0, '/home/usr/local/image ')     3, set the Linux import module path         Echo $pythonpath         Export pythonpath= $pythonpath: '/home/usr/local/ Image '     4, if the program has referenced the module, but the module has been Modified. Need to re-import modules:        can be done using reload (module), similar to the case cache after import operation  7, pyc file     1, concept         PYC files are representations of the Pycodeobject object on the hard Disk. Generate PYc files:    2, pyc file three functions         1, creation time, py file newer than PYc file, then new generation PYc file         2, Magic Num Does the Pre-run version detection, the version is different from the new production pyc        3, Pycodeobject object         4, during the run, the compilation result is The Pycodeobject object will only exist in memory, and when the Python code of this module is executed, it will save the compiled result to the PYc file so that it can be loaded into memory without compiling the next Time.         5, This Pycodeobject object contains the strings in the Python source code, the constant values, and the bytecode instructions generated by the syntax Parsing. The Pycodeobject object also stores theThe corresponding relationship between the bytecode instruction and the original code line number, so that when an exception occurs, you can indicate which line of code is Located.  8, import Directive     1, Import instruction is used to load module, if necessary, will also do Compile. But the import command, but also do an important thing is to import the module code to execute it once, this matter is very important. Python is interpreted as executing, and even functions are created only when they are executed. If the module code is not executed once, then the functions inside the module cannot be created, let alone to invoke these Functions.      2, Another important function of code execution is to create the function defined within the module and the symbolic name of the various objects (that is, the variable Name) in the namespace of the modules, and bind it to the object so that the other module To refer to these objects through variable Names.      3, The Python virtual machine will also cache the Already-import module into a global module collection Sys.modules. The advantage of this is that if the program imports the module again in another place, the Python virtual machine simply returns the module object cached in the global module Collection.   -------------------closures-------------------1, concept:    Intrinsic functions to reference variables in the scope of an external function (non-global variables), The inner function is called a closure. 2. case:    #外部函数     def counter (start=0):        #自由变量: define a list       &N Bsp Count = [start]        #内部函数         def incr ():            count[0] + + 1            return count[0] #返回列表结果         #返回函数         return incr     #变量接受一个函数     con = counter (5)      #运行接收到的函数     Print con ()      print con ()   ------------------ -adorner-------------------1, Reference general function handling     1, common processing functions:        1, introduction of the journal         2, function execution Time statistics         3, pre-function processing         4, perform function after cleaning function         5, permission check and other fields View         6, cache  2, case: No parametric function     #引用对应的包     from time import ctime   &nbs P #修饰器     def timefun (func):        def Wrappedfunc ():          &NBSP ; Print ("%s called at%s"% (func.__name__,ctime ()))             return func ()     &NBSP ;   return wrappedfunc     @timefun     def foo ():        print ("I am Foo")      Foo()  3, case: Decorator and Closure mix      #coding =utf-8     from time import time     def Logged (when):        def log (f, *args, **kargs):            Print ("fun:% s  args:%r  kargs:%r "% (f, args, kargs))             #%r string while displaying the original object type  &nbsp ;       def pre_logged (f):            def wrapper (*args, **kargs):                log (f, *args, **kargs)                 R Eturn F (*args, **kargs)             return wrapper         def Post_ Logged (f):            def wrapper (*args, **kargs):                Now=time ()                 try:          &NB Sp       &nbsp Return f (*args, **kargs)                 finally:                    log (f, *args, **kargs)                   & nbsp Print ("time delta:%s"% (time ()-now))             return wrapper        TR y:            return {"pre":p re_logged, "post":p ost_logged}[when]      &NBSP ; Except keyerror, e:            raise ValueError (e), ' must be ' pre ' or ' post '    &n Bsp @logged ("post")     def fun (name):        print ('%s '% (name))      Fun ("hello word! ")   -------------------built-in functions-------------------1, concept:    1, build-in function, start the Python interpreter, enter dir ( builtins), you can see many of the properties and functions that are loaded by default after the start of the Python interpreter, which are called built-in functions, because they are used more in programming, the CPython interpreter implements these functions with the C language, which is loaded by default when the interpreter is Started.      2, Many of these functions are notShould remember, development is not all used, to be used to help (function), see how to use, or combined with Baidu query can, here introduce some of the commonly used built-in Functions.  2, range    1, help (range):        range (stop), List of integers    &NBSP ;      range (start, stop[, step), List of integers       2, parametric analysis:    &NBSP ;      1, start: counting starts from Start. The default is starting from 0. For example, range (5) is equivalent to range (0, 5).         2, stop: ends with stop, but does not include stop. for example: range (0, 5) is [0, 1, 2, 3, 4] without 5.         3, step: the spacing of each jump, the default is 1. For Example: range (0, 5) is equivalent to range (0, 5, 1).     3, example:        A = range (5)         list (a)  3, map    1, H ELP (map):        Map (...)         map (function, sequence[, sequence, ...]) list    2, parametric analysis:      & nbsp 1, Function: is a functions         2, sequence: is one or more sequences, depending on the function requires a few parameters         3, The return value is a list    3, syntax:  &NBSp     Each element in the parameter sequence calls a function, which returns a list containing the return value of each Function.     4, example         #函数需要一个参数         map (lambda x:x*x, [1, 2, 3])   &NB Sp     [1, 4, 9]         #函数需要两个参数         map (lambda x, y:x+y, [1, 2, 3], [4, 5, 6])         [5, 7, 9]         #函数为None, equivalent to merging parameters Ganso     &NB Sp   Map (None, [1, 3, 5, 7, 9], [2, 4, 6, 8, ten])         [(1, 2), (3, 4), (5, 6), (7, 8), (9)]&n bsp;        #两个序列参数个数不一致时, small number of none        map (None, [1, 3, 5, 7, 9], [2, 4, 6]) &n Bsp       [(1, 2), (3, 4), (5, 6), (7, none), (9, none)] 4, filter    1, help (filter):  &nbsp ;     Filter (...)         filter (function or None, sequence), list, tuple, or string       &NBS P Return those items of sequence for Which function (item) is true.  if        function is None, return to the items is true.  If sequence is a tuple        or string, return the same type, else return a list.    2, parameter analysis:        1, Function: accepts a parameter, returns a Boolean value of TRUE or false        2, sequence: the sequence can be str,tuple, list    3, Grammar         The filter function calls the function functions for each element in the sequence parameter sequence, and the result that is returned contains the element that invokes the result to True. The type of return value is the same as the type of parameter sequence     4, example         filter (lambda x:x%2, [1, 2, 3, 4])     &NBSP ;   [1, 3]         filter (None, "she")         ' She '  5, reduce  &n Bsp 1. Help (reduce):        reduce (...)             reduce (function, sequence[, initial]), value       &NBS P     Apply A function of arguments cumulatively to the items of a sequence,  &nbsp         from left-to-right, as-to-reduce the sequence to a single value.            for example, reduce (lambda x, y:x+y, [1, 2, 3, 4, 5]) calculates            (((((1+2) +3) +4) +5) .  If Initial is present, it is placed before the items            The sequence in the calculation, and serves as a default when the            sequence are EMP ty.    2, parametric analysis:        1, function: two parameters         2, sequence: the sequence can be str, tuple,list        3, initial: Fixed initial value      3, grammar         Reduce takes an element from the sequence in turn and invokes function again with the result of the last call to Function. The first call to function, if supplied with the initial parameter, calls function with the first element in sequence and initial as a parameter, otherwise the function is called with the first two elements in the sequence Sequence. Note that function functions cannot be none.     4, examples         reduce (LAMBDA x, y:x+y, [1,2,3,4])     &NBSp   10         reduce (LAMBDA x, y:x+y, [1,2,3,4], 5)         15&NBSP;&NBSP ;       Reduce (lambda x, y:x+y, [' aa ', ' bb ', ' cc '), ' dd ')         ' DDAABBCC '  6, sorte d    1, help (sorted):        sorted (...)             sorted (iterable, cmp=none, key=none, reverse=false)--new sorted list    2, parametric analysis:        Custom CMP comparison function, return three cases:            X<y return -1  & nbsp         X>y return 1            x==y return 0    3, example     &N Bsp   def cmp_ignore_case (s1, s2):            u1 = s1.upper ()         &N Bsp   U2 = S2.upper ()             If U1 < u2:            &N Bsp   return-1            If U1 > u2:                return 1          & nbsp return  -------------------iterators-------------------1, the concept:    iterator is only a container object, it implements the iterator Protocol.  2, Next ():    1, returns the next element of the container     2, throws a Stoplteration exception at the end  3, ITER ():    The data is converted to a Drop-down format by iter, returning the device itself  -------------------generator-------------------1, the concept:    generator is such a function, It remembers where in the function body the last time it was Returned. A second (or Nth) call to the generator function jumps to the middle of the function, and all local variables that were last called remain Unchanged.  2, features:     1. The generator is a function, and the parameters of the function are Preserved.      2. When iterating to the next call, the parameters used are left for the first time, that is, the parameters of all function calls are preserved the first time they are called, not the newly created      3. save memory  3, case:    #generation .py    def Gen ():        for x in xrange (4):  &nbsp ;         TMP = yield x               if tmp = = "hello":  & nbsp             print "world"       &NBSP;     else:                print "itcastcpp", str (tmp)      #执行到yield时, the function of the Gen function is temporarily saved, the value of x is returned; TMP receives the next C.send ("python"), the value sent by send, c.next () equivalent c.send (None)      > >>from Generation import gen    >>>c=gen ()     >>>c.next ()     0& nbsp   >>>c.next ()     itcastcpp none    1    >>>c.send ("python")     Itcastcpp python    2 4, scenarios:    1, When you need a very large list, to reduce memory consumption, you can use the generator     Case:         class A (object):               def __init__ (self, i): & nbsp               from time import sleep, time            &NB Sp   Sleep (i)                 print (time ())          1, F or C in [A (i) for I in range (5)]:[] is generated by iterating over an iterative object to generate a list        2, for C in (A (i) as I in range (5)): () is to return directly to the iteration object  5, summary:    1. Infinite recursion becomes possible     2, greatly reduces the overhead of thread or inter-process context switching     3, user manually specifies thread invocation, avoids lock overhead  ------------------- Context-------------------  -------------------functools function-------------------1, concept:    Functools is python2.5, Some tool functions are put in this package.  2, operations:    1, import functools: refer to the corresponding package     2, dir (functools): view the corresponding tool function  1, partial function (partial Function) in the Package:     1, concept:        Setting a default value for some parameters of a function, returning a new function, it would be easier to call the new Function.     2, example:        Import functools        def Showarg (*args, **kw):            print (args)             print (kw)      &NBS P   p1=functools.partial (showarg)         P1 ()         P1 (4,5,6)   &N Bsp     P1 (a= ' python ', b= ' itcast ')      &nbsp   p2=functools.partial (showarg, a=3,b= ' Linux ')         P2 ()         P2 (+) & nbsp       P2 (a= ' python ', b= ' itcast ')  2, wraps functions:    1, concept:        when using adorners, There are some details that need to be noticed. For example, a decorated function is actually a different function (function names and other functions will change). Python's Functools Package provides an adorner called wraps to eliminate such side effects     2, example:        Import functools        DEF note (func):            "note function"           & nbsp @functools. Wraps (func)             def wrapper ():            &N Bsp   "wrapper function"                 Print (' note something ')     &NBS P           return func ()             return wrapper   &nbsp ;     @note         DEF Test ():      &nbsp     "test function"             Print (' I am Test ')          Test ()         Print (test.__doc__)

Python Learning summary (function advanced)

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.