Adorner: Essentially a function (decorating other functions): Adding ancillary functionality to other functions.Principle:
Cannot modify the source code of the decorated function
Cannot modify the calling method of the decorated function
Realize the knowledge reserve of the Adorner (decorator):
function is variable
Higher order functions
Nested functions
function is variable:
Pass the function name as a
) Stop_time=time.time ()Print('run time is%s'% (stop_time-start_time)) returnResreturnThe return value of the wrapper #timmer () points to the memory address of the function wrapper () @timmerdeffoo (): Time.sleep (3) Print('From foo') foo ()With reference decoratordefAuth (driver='file'):#any parameter can be added here, with all the reference adorners up to three layers defAuth2 (func):#func fixed here, not allowed to add value, only is the memory address of the decorated function
A simple memory cache. Can be used to cache arbitrary function methods in memory.#!/usr/bin/python ImportFunctools fromThreadingImportRlockImportLogging LOGGER= Logging.getlogger (__name__)classCachenullvalue (object):Pass_null=Cachenullvalue ()classCache (object):def __init__(Self, cache_limit=1000): Self._cache={} self._queue=[] Self.cache_limit=Cache_limit Self._lock=Rlock ()def __getitem__(self, name): With Self._lock:returnself._cache.get (name,
the memory address of the Deco () One A - deftest1 (): -Time.sleep (3) the Print("In the test1") - - - deftest2 (): +Time.sleep (3) - Print("In the test2") + A atTimer (test1)#test1 memory address assigned to Func, returns the memory address of Deco () - Print(Timer (test1))#returns the memory address of the Deco () -Test1 = Timer (test1)#memory address assigned to Test1 -Test1 ()#equivalent to performing deco () - - timer (test2) inTest2 =timer (test2) - test2 () to + Print("--
1. The higher order function receives the function as the parameter, returns the function.2. Function closure3. Receive a function as a parameter, wrap it, and return a wrapper function#!/usr/env/python#-*-coding:utf-8-*- from __future__ Importprint_functiondefF1 (x):returnX*2defNew_fn (f):deffn (x):Print("Pager"+f.__name__+'()') returnf (x)returnFNA= NEW_FN (F1) (2)Print(a)Print("##################") b= F1 (2)Print(b) @new_fndefF1 (x):returnX*
What is a python adorner?An adorner is actually a function, a function that wraps a function, returns a modified function object, assigns it the original identifier, and permanently loses access to the original function object. eg: when you need to add the same functionality to FUNC1 and FUNC2, you can add the entire function once in the outer. The way the adorner connects to a function is done with the @+ adorner name in the previous line of the func
() func (*args,**kwargs) stop_time=time.time () print (' Thefunc runtimeis%s ' % (stop_time-start_timereturn deco # # # # #想要哪个函数调用装饰器就在哪个头部加这个内容 # # # # @timer = = Test1 = Timer (test1) @timer def test1 (): Time.sleep (3) print (' This is TE St1 ') def test2 (name,age): Time.sleep (3) print (' This is Test2 ') print (' name:%s,age:%s '% (name,age)) test1 () #test1 Has not been changed, and the calling method has not been changed test2 (' Thieves ', 18)Above three examples if the decorated fun
("index") Index (' W ', ' Z ') #执行过程 1. The interpreter interprets the Python code from the top to first load the HS1 function into memory, and then add the HS2 and ZSQ functions to the memory. 2, Encounter @zsq (HS1, HS2), the interpreter will first execute ZSQ (HS1, HS2), HS1 and HS2 as parameters to zsq assigned to zsq the formal parameters hs_1 and hs_2 (here equivalent to @zsq = ZSQ (HS1,HS2)). 3. Load the home function into memory and ret
, Func () is just a string of strings, and func () does not call executionStop_time =time.time ()Print("The func run time is%s"% (Stop_time-start_time)) returnDeco@timer#Test1=timer (test1)deftest1 (): Time.sleep (3) Print("In the test1") test1 ()in is 3.0149574279785156 ResultIntroduce @timer , which is equivalent to the Test1=timer (test1) statement.3. An adorner with an indeterminate number of parameters1 Import Time2 3 defTimer (func):#Timmer (test1) Func=test14 defDeco (*args,**Kwarg
function as a "variable", let's first talk about the mechanism of Python memory storage variables.When a variable x=1 is set, memory is considered a big house, and when it comes to a room, it will be free to place the variable value 1 into the room and affix the number x.If it is x=1,y=x, that is the variable value 1 The room will have two numbers, namely xy. :In the Python memory recycling mechanism, when
that preserves the binding of a free variable that defines a function, so that when the function is called, the scope of the definition is not available, but those bindings are still available.Nonloal statementA local variable in a function can be used by a function in a function, but if an assignment statement is used, it is necessary to define the local variable as a free variable, and the function of Nonloal is to mark the variable as a free variable.There is no nonlocal in Python2 but you c
The first step simple function1 " " simple function: Call two times " " 2 def myfunc (): 3 Print ('myfunc () called. ' )45myfunc ()6 myfunc ()The second step adorner provides additional functionality for the calling function1 " "Replace function (decoration)2 The parameter of the adornment function is the decorated function object, returning the original function object3 The material statement of the ornament; myfunc = Deco (myfunc)" "4 defDeco (func):5 Print("before MyFunc () called.")6
1 defDeco (func):2 def_deco ():3 Print("before")4 func ()5 Print("End")6 #Return func here does not need to be returned7 return_deco#This is not _deco ()8 9 @decoTen defmyfunc (): One Print("clled") A -MyFunc ()With the parameterdefDeco (func):def_deco (A, b):Print("before") ret=func (A, b)Print("End") #Return func here does not need to be returned return_deco#This is not _deco ()@decodefMyFunc (A, b):Print("clled"Ab)returnABmyfunc (7,15)
Simple adorner code (for decorated functions with parameters and return values):#!_*_ coding=utf-8 _*_#!/usr/bin/env pythondef outer (fun): Def wrapper (Var): print "pre-decoration" Resulf = Fun (var ) print "Post Deco" return Resulf return Wrapper@outerdef Func1 (Var): print "This is Func1", var return "T He is Func1 return "Resulf = Func1 (" WLW ") print Resulf execution result: #这是Func1经过装饰后的结果装饰前this is Func1 WLW after decoration # This is the return value of the accepted function this is th
IteratorsAn object that can directly act on a for loop is called an iterative object (iterable).An object that can be called by the next () function and continually returns the next value is called an iterator (Iterator).All iterable can be converted to iterator via the built-in function iter ().names = ITER (['Sun','IBM','Sunny'])Print(names)Print(names.__next__())Print(names.__next__())Print(names.__next__())Print(names.__next__())#first output Print iterator object#the next method for the No.
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.