A variety of adorners in Python detailed

Source: Internet
Author: User
Python adorner, divided into two parts, one is the definition of the adorner itself, one is the definition of the adorner object.

A functional decorator: the adorner itself is a function.

1. Decorative function: The object being decorated is a function

[1] Adorner no parameters:

A. The adorned object has no parameters:

The code is as follows:


>>> def Test (func):
Def _test ():
print ' Call the function%s (). ' %func.func_name
return func ()
Return _test

>>> @test
Def say (): Return ' Hello World '

>>> Say ()
Call the function say ().
' Hello World '
>>>

B. The decorated object has parameters:

The code is as follows:


>>> def Test (func):
def _test (*args,**kw):
print ' Call the function%s (). ' %func.func_name
return func (*ARGS,**KW)
Return _test

>>> @test
def left (Str,len):
#The parameters of _test can is ' (Str,len) ' in the case.
return Str[:len]

>>> left (' Hello World ', 5)
Call the function left ().
' Hello '
>>>

[2] The adorner has parameters:

A. The adorned object has no parameters:

The code is as follows:


>>> def Test (printresult=false):
def _test (func):
Def __test ():
print ' Call the function%s (). ' %func.func_name
If Printresult:
Print func ()
Else
return func ()
Return __test
Return _test

>>> @test (True)
Def say (): Return ' Hello World '

>>> Say ()
Call the function say ().
Hello World
>>> @test (False)
Def say (): Return ' Hello World '

>>> Say ()
Call the function say ().
' Hello World '
>>> @test ()
Def say (): Return ' Hello World '

>>> Say ()
Call the function say ().
' Hello World '
>>> @test
Def say (): Return ' Hello World '

>>> Say ()

Traceback (most recent):
File " ", line 1, in
Say ()
TypeError: _test () takes exactly 1 argument (0 given)
>>>


The last two examples from the above code show that when the adorner has parameters, even if you enable the adorner's default parameters, and no additional values are passed in, there must be a pair of parentheses, otherwise the compiler will pass Func directly to test () instead of passing it to _test ()

B. The decorated object has parameters:

The code is as follows:


>>> def Test (printresult=false):
def _test (func):
def __test (*args,**kw):
print ' Call the function%s (). ' %func.func_name
If Printresult:
Print func (*args,**kw)
Else
return func (*ARGS,**KW)
Return __test
Return _test

>>> @test ()
def left (Str,len):
#The parameters of __test can is ' (Str,len) ' in the case.
return Str[:len]

>>> left (' Hello World ', 5)
Call the function left ().
' Hello '
>>> @test (True)
def left (Str,len):
#The parameters of __test can is ' (Str,len) ' in the case.
return Str[:len]

>>> left (' Hello World ', 5)
Call the function left ().
Hello
>>>



2. Decoration class: The object being decorated is a class

[1] Adorner no parameters:

A. The adorned object has no parameters:

The code is as follows:


>>> def Test (CLS):
Def _test ():
Clsname=re.findall (' (\w+) ', repr (CLS)) [-1]
print ' Call%s.__init (). ' %clsname
Return CLS ()
Return _test

>>> @test
Class Sy (object):
Value=32


>>> S=sy ()
Call Sy.__init ().
>>> s
<__main__.sy Object at 0x0000000002c3e390>
>>> S.value
32
>>>


B. The decorated object has parameters:

The code is as follows:


>>> def Test (CLS):
def _test (*args,**kw):
Clsname=re.findall (' (\w+) ', repr (CLS)) [-1]
print ' Call%s.__init (). ' %clsname
Return CLS (*ARGS,**KW)
Return _test

>>> @test
Class Sy (object):
def __init__ (Self,value):
#The parameters of _test can is ' (value) ' in the case.
Self.value=value


>>> s=sy (' Hello World ')
Call Sy.__init ().
>>> s
<__main__.sy Object at 0x0000000003af7748>
>>> S.value
' Hello World '
>>>


[2] The adorner has parameters:

A. The adorned object has no parameters:

The code is as follows:


>>> def Test (printvalue=true):
def _test (CLS):
Def __test ():
Clsname=re.findall (' (\w+) ', repr (CLS)) [-1]
print ' Call%s.__init (). ' %clsname
Obj=cls ()
If Printvalue:
print ' value =%r '%obj.value
return obj
Return __test
Return _test

>>> @test ()
Class Sy (object):
def __init__ (self):
Self.value=32


>>> S=sy ()
Call Sy.__init ().
Value = 32
>>> @test (False)
Class Sy (object):
def __init__ (self):
Self.value=32


>>> S=sy ()
Call Sy.__init ().
>>>

B. The decorated object has parameters:

The code is as follows:


>>> def Test (printvalue=true):
def _test (CLS):
def __test (*args,**kw):
Clsname=re.findall (' (\w+) ', repr (CLS)) [-1]
print ' Call%s.__init (). ' %clsname
Obj=cls (*ARGS,**KW)
If Printvalue:
print ' value =%r '%obj.value
return obj
Return __test
Return _test

>>> @test ()
Class Sy (object):
def __init__ (Self,value):
Self.value=value


>>> s=sy (' Hello World ')
Call Sy.__init ().
Value = ' Hello World '
>>> @test (False)
Class Sy (object):
def __init__ (Self,value):
Self.value=value


>>> s=sy (' Hello World ')
Call Sy.__init ().
>>>


Second, class decorator: The adorner itself is a class, borrowing __init__ () and __call__ () to achieve the function

1. Decorative function: The object being decorated is a function

[1] Adorner no parameters:

A. The adorned object has no parameters:

The code is as follows:


>>> class Test (object):
def __init__ (Self,func):
Self._func=func
def __call__ (self):
Return Self._func ()


>>> @test
Def say ():
Return ' Hello World '

>>> Say ()
' Hello World '
>>>

B. The decorated object has parameters:

The code is as follows:


>>> class Test (object):
def __init__ (Self,func):
Self._func=func
def __call__ (self,*args,**kw):
Return Self._func (*ARGS,**KW)


>>> @test
def left (Str,len):
#The parameters of __call__ can is ' (Self,str,len) ' in the case.
return Str[:len]

>>> left (' Hello World ', 5)
' Hello '
>>>

[2] The adorner has parameters

A. The adorned object has no parameters:

The code is as follows:


>>> class Test (object):
def __init__ (self,beforeinfo= ' Call function '):
Self.beforeinfo=beforeinfo
def __call__ (Self,func):
Def _call ():
Print Self.beforeinfo
return func ()
Return _call


>>> @test ()
Def say ():
Return ' Hello World '

>>> Say ()
Call function
' Hello World '
>>>

Or:

The code is as follows:


>>> class Test (object):
def __init__ (self,beforeinfo= ' Call function '):
Self.beforeinfo=beforeinfo
def __call__ (Self,func):
Self._func=func
Return Self._call
def _call (self):
Print Self.beforeinfo
Return Self._func ()


>>> @test ()
Def say ():
Return ' Hello World '

>>> Say ()
Call function
' Hello World '
>>>

B. The decorated object has parameters:

The code is as follows:


>>> class Test (object):
def __init__ (self,beforeinfo= ' Call function '):
Self.beforeinfo=beforeinfo
def __call__ (Self,func):
def _call (*args,**kw):
Print Self.beforeinfo
return func (*ARGS,**KW)
Return _call


>>> @test ()
def left (Str,len):
#The parameters of _call can is ' (Str,len) ' in the case.
return Str[:len]

>>> left (' Hello World ', 5)
Call function
' Hello '
>>>

Or:

The code is as follows:


>>> class Test (object):
def __init__ (self,beforeinfo= ' Call function '):
Self.beforeinfo=beforeinfo
def __call__ (Self,func):
Self._func=func
Return Self._call
def _call (self,*args,**kw):
Print Self.beforeinfo
Return Self._func (*ARGS,**KW)


>>> @test ()
def left (Str,len):
#The parameters of _call can is ' (Self,str,len) ' in the case.
return Str[:len]

>>> left (' Hello World ', 5)
Call function
' Hello '
>>>


2. Decoration class: The object being decorated is a class

[1] Adorner no parameters:

A. The adorned object has no parameters:

The code is as follows:


>>> class Test (object):
def __init__ (SELF,CLS):
Self._cls=cls
def __call__ (self):
Return Self._cls ()


>>> @test
Class Sy (object):
def __init__ (self):
Self.value=32


>>> S=sy ()
>>> s
<__main__.sy Object at 0x0000000003aafa20>
>>> S.value
32
>>>

B. The decorated object has parameters:

The code is as follows:


>>> class Test (object):
def __init__ (SELF,CLS):
Self._cls=cls
def __call__ (self,*args,**kw):
Return Self._cls (*ARGS,**KW)


>>> @test
Class Sy (object):
def __init__ (Self,value):
#The parameters of __call__ can is ' (self,value) ' in the case.
Self.value=value


>>> s=sy (' Hello World ')
>>> s
<__main__.sy Object at 0x0000000003aafa20>
>>> S.value
' Hello World '
>>>

[2] The adorner has parameters:

A. The adorned object has no parameters:

The code is as follows:


>>> class Test (object):
def __init__ (Self,printvalue=false):
Self._printvalue=printvalue
def __call__ (SELF,CLS):
Def _call ():
Obj=cls ()
If Self._printvalue:
print ' value =%r '%obj.value
return obj
Return _call


>>> @test (True)
Class Sy (object):
def __init__ (self):
Self.value=32


>>> S=sy ()
Value = 32
>>> s
<__main__.sy Object at 0x0000000003ab50b8>
>>> S.value
32
>>>

B. The decorated object has parameters:

The code is as follows:


>>> class Test (object):
def __init__ (Self,printvalue=false):
Self._printvalue=printvalue
def __call__ (SELF,CLS):
def _call (*args,**kw):
Obj=cls (*ARGS,**KW)
If Self._printvalue:
print ' value =%r '%obj.value
return obj
Return _call


>>> @test (True)
Class Sy (object):
def __init__ (Self,value):
#The parameters of _call can is ' (value) ' in the case.
Self.value=value


>>> s=sy (' Hello World ')
Value = ' Hello World '
>>> s
<__main__.sy Object at 0x0000000003ab5588>
>>> S.value
' Hello World '
>>>

Summary: When the "1" @decorator is followed by no parentheses (that is, when the adorner has no parameters), the effect is equivalent to defining the Func or CLS before performing the assignment operation Func=decorator (func) or Cls=decorator (CLS);

When the "2" @decorator is followed by parentheses (that is, when the adorner has parameters), the effect is equivalent to defining the Func or CLS before performing the assignment operation Func=decorator (Decoratorargs) (func) or Cls=decorator ( Decoratorargs) (CLS);

"3" When the Func or CLS is re-assigned, the Func or CLS at this time is no longer the Func or CLS as originally defined, but an executable, you only need to pass in parameters to invoke, func (args) = return value or output, cls (args) = Object of the CLS;

"4" Finally the execution body returned by the assignment is varied, can be a closure or an external function, and when it is decorated with a class, it can also be a class internal method, function;

"5" In addition to really understand the adorner, be sure to understand func.func_code.co_varnames,func.func_defaults, through which you can restore Func's argument list beyond the definition of func In addition, the keyword parameter is the result of the invocation, and not because of the Func definition, in the definition of Func, only the parameters with the default values are concatenated, they are not necessarily the keyword arguments, because you can still pass them by location.

  • 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.