python-Advanced-Decorator Summary, reproduced

Source: Internet
Author: User

This article was reproduced from: http://www.wklken.me/posts/2012/10/27/python-base-decorator.html

Basic concepts

Specific concept yourself Google

The adorner is a well-known design pattern, which is often used for scenes with cut-off requirements, with more classic insert logs, performance tests, transaction processing, web rights checks, caches, and so on.

Well-known examples are coffee, sweetened coffee, and coffee with milk.
In essence, or coffee, just on the original thing, did the "decoration" to add some features or features.

such as logging, some functions need to be recorded

Stupid way, each function to add code, if the code changed, it is sad to urge the

Decorator's approach, define a special logging decorator, decorate the required functions, and fix

Advantages

Draw out the same code that is not relevant to the function itself in a large number of functions and continue to reuse

That is, the function can be "decorated" as a completely different behavior, effectively orthogonal decomposition of business logic, such as the use of permissions and authentication from the business Independent

In summary, the function of an adorner is to add additional functionality to an already existing object.

adorners in Python

In Python, the adorner implementation is very convenient.

The reason: functions can be thrown away.

function as an object:

A. can be assigned to other variables, which can be used as the return value B. Can be defined within another function

Def:

An adorner is a function, a function used to wrap a function, the adorner is called when the function declaration is completed, a modified function object is returned after the call, the original identifier is re-assigned, and the access to the original function object is permanently lost (the declared function is replaced by a function that has been decorated by the adorner)

When we apply an ornament method to a method, we actually change the entry point of the function code block referenced by the name of the decorated function, so that it points back to the function entry point returned by the adornment method.

Thus we can use decorator to change the function of an existing function, add various operations, or completely change the original implementation

Classification:

The adorner is divided into parameter-free decorator with parameter decorator

* Parameterless decorator generates a new adorner function * has the parameter decorator to decorate, the adornment function processes the parameter first, regenerates into a new adorner function, then decorates the function

The decorator has the parameter/no parameter, the function has the parameter/no parameter, the combination total 4 kinds

Specific definition:

Decorator method

A. The method to be decorated as the input parameter,

B. Any action can be performed in the body of the function (it can be imagined that the power is powerful and there are many scenarios)

C. Just be sure to return an executable function (can be the original input parameter function, or a new function)

No parametric adorner – package parameterless function

No need for processing and optimization of parameters

Decorator(func):    func@decoratorfoopassfoo()   

Foo ()
Equivalent to:

Decorator(foo)foo()    
Parameterless Adorner – Package with parametric function
DefDecorator_func_args(Func):DefHandle_args(*Args,**kwargs):  #处理传入函数的参数 print func (*args **kwargs)  #函数调用 print  "end" return handle_args @decorator_func_args Span class= "K" >def foo2 (ab< Span class= "o" >=2): print a span class= "n" >bfoo2 (1)      

Foo2 (1)
Equivalent to

Decorator_func_args(foo2)foo2(1)      
With parametric adorner – package parameterless function
Decorator_with_params(arg_of_decorator):newdecorator(funcnewdecorator@ Decorator_with_params("Deco_args")Foo3passFoo3()    

Different from the previous: a layer more than the previous layer of encapsulation, the first pass the parameters, and then pass the function of the name

The first function, Decomaker, is a decorative function whose parameters are used to enhance the "enhanced decoration". Since this function is not a decorated function object, you must internally create at least one function that accepts the decorated function, and then return this object (in fact foo3= Decorator_with_params (arg_of_decorator) (FOO3) at this time)

With parametric adorner – package with parametric function
DefDecorator_whith_params_and_func_args(Arg_of_decorator):DefHandle_func(Func):DefHandle_args(*Args,**Kwargs):Print"Begin"Func(*Args,**Kwargs)Print"End"print arg_of_decorator, func, args,Kwargs return Handle_args return handle_func@decorator_whith_params_and_func_args("123")def Foo4(a , b=2): print "Content"Foo4(1, b=3)  
Built-in adorners

There are three built-in decorators: Staticmethod,classmethod, properties

ClassA():@staticmethodDefTest_static():Print"Static"Deftest_normal (selfprint  "normal"  @classmethod def test_class (clsprint  "class"  clsa = a () Atest_static () a. Test_static () a. Test_normal () a. Test_class ()             

Results:

Staticstaticnormalclass __main__. A

A.test_static

The instance method defined in the Staticmethod class becomes a static method

Basically it's almost the same as a global function (no need to pass in self, only general arguments), but it can be called through an instance object of a class or class, and no parameters are implicitly passed in.

Static methods similar to static languages

B.test_normal

Common Object methods:
A normal object method requires at least one self parameter, which represents the Class object instance

C.test_class

The instance method defined in the class becomes a class method

Classmethod need to pass in class objects, which can be called through instances and class objects.

is a class-related method that can be called from a class or class instance and implicitly passes the class object (not an instance object of Class) as the first parameter.

This may be a bit odd, but if you figure out that Python is a real object in memory, rather than a static language that only exists during compilation, it's a good idea. The normal method is to have a method associated with an instance object of a class, call through the class instance object, and implicitly pass the instance object as the first parameter, which is also similar to other languages.

D. Differences

Staticmethod,classmethod is equivalent to a global method, typically used in an abstract class or parent class. Generally not related to a specific class.

Class methods require additional class-variable CLS, and when a subclass inherits, the class variable passed in by the calling class method is a subclass, not a parent class.

Both class methods and static methods can be accessed through class objects and instance objects of the class

The method of definition, the parameters passed in, and the calling method are different.

E.property

Operations on class properties, similar to those defined in Java Getter/setter

ClassB():Def__init__(Self):Self.__prop=1@propertyDefProp(self): print  "call get" return Span class= "BP" >self. __prop  @prop. Setter def prop ( Selfvalue): print  "call Set" Span class= "BP" >self. __prop = value  @prop. deleter def  (selfprint  "Call del" Span class= "K" >del self. __prop                 
Other

A. The order of the adorners is important and needs attention

@A@B@c():  

Equivalent to

A(B(C(F)))      

The B.decorator can be a module-level method or a class method.

The C.functools module provides two adorners.
This module was added after Python 2.5.

Functools.wraps (func)
Total_ordering (CLS)
This specific to see it, the follow-up used to supplement

A simple example

Controls whether to count time when calling a function through a variable

#!/usr/bin/env python#-*-Coding:utf-8-*-# @author: [Email protected]# @version: A test of decorator# @date: 20121027# @desc: Just a testImportLoggingFromTimeImportTimeLogger=Logging.GetLogger()Logger.SetLevel(Logging.DEBUG)Is_debug=TrueDefCount_time(Is_debug):DefHandle_func(Func):DefHandle_args(*Args,**Kwargs):IfIs_debug:Begin=Time()Func(*Args,**Kwargs)Logging.Debug("["+Func.__name__+"],"+Str(Time()-Begin))Else:Func(*Args,**Kwargs)ReturnHandle_argsReturnHandle_funcDefpr():ForIInchRange(1,1000000):I=I*2print  "Hello World" def test (): span class= "n" >pr ()  @count_time  (is_debug ) def test2 (): pr  ()  @count_time  (falsedef test3 (): pr () if __name__ ==  "__main__" : test () test2 () test3 ()   

Results:

Hello Worldhello worlddebug:root:[test2]-0.0748538970947hello World

The end!

Wklken

Gighub:https://github.com/wklken

blog:http://wklken.sinaapp.com/

2012-10-27

Reprint please indicate the source, thank you!

python-Advanced-Decorator Summary, reproduced

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.