[Python Introductory and advanced notes] Summary __python of python-decorator decoration device

Source: Internet
Author: User
Tags instance method wrapper

http://blog.csdn.net/wklken/article/details/8118942


-----------------------------------------------

It seems not easy to find a place to be happy coding.

Impulsive, but the posterior has been broken, do what you want to do, always pay some price, adhere to it, can only.

Under the trough, this week all sorts of things, make like leapfrog dozen strange and difficult. Saturday, went three hours, returned three hours, defeated but return, but still learned a lot of things.

The gap is still there, although self-confidence can be in the shortest possible time, but, the need for costs.

In short, seemingly wrong timing, hey above nonsense, into the business

Met in Saturday, a week busy, today a little bit, to fill the whole, data mainly from books, Network &self.coding (). If you have any questions, please correct me. Basic Concepts

Specific concept of their own Google

The adorner is a very famous design pattern, often used in the aspect of the scene, the more classic has inserted log, performance testing, transaction processing, Web permissions check, cache and so on.

A famous example is coffee, coffee with sugar, coffee with milk. In essence, or coffee, but in the original thing, did "decorate", so that the addition of some features or features.

For example logging, some functions need to be logged

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

Decorator, define a specialized logging adorner, decorate the desired function, and fix the advantages

Extract the same code that is irrelevant to function itself in a large number of functions and continue to reuse

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

In summary, the role of adorners is to add extra functionality to existing objects. adorners in Python

In Python, the adorner implementation is very convenient

The reason: The function can be thrown to throw.

function as an object:

A. can be assigned to other variables and can be used as return value

B. Can be defined in another function

Def:

An adorner is a function, a function used to wrap a function, the adorner is invoked when the function declaration is complete, after which it returns a modified function object, assigns it to the original identifier, and permanently loses access to the original function object (the declared function is replaced with a function 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 decorated function name to point it back to the function entry point returned by the adornment method.

We can use decorator to change the function of an existing function, add various operations, or completely change the original implementation Category:

The adorner is divided into decorator without parameters, with parameters decorator

* No parameter Decorator

generate a new adorner function

* There are ginseng decorator

, decorative function first process parameters, regenerate into a new adorner function, and then decorate the function

The adorner has the parameter/no parameter, the function has the parameter/the parameter, the combination altogether 4 kinds of concrete definitions:

Decorator method

A. To decorate the method as input parameters,

B. You can do whatever you want in the body of the function (imagine that it's powerful, there are many scenarios),

C. Just make sure that you finally return an executable function (which can be the original input parameter function, or a new function) without parameter adorners-wrapper without parameter function

No need to process and optimize for parameters

def decorator (func):
    print "Hello" return
    func

@decorator
def foo ():
    pass

foo ()

Foo () is equivalent to:

foo = decorator (foo)
foo ()
non-parametric adorner-packing with parameter function
def Decorator_func_args (func):
    def handle_args (*args, **kwargs): #处理传入函数的参数
        print "Begin"
        func (*args , **kwargs)   #函数调用
        print "End" return
    Handle_args


@decorator_func_args
def foo2 (A, b=2):
    print A, b

foo2 (1)

Foo2 (1) is equivalent to

Foo2 = Decorator_func_args (foo2)
Foo2 (1)
with parameter adorner-wrapper without parameter function
def decorator_with_params (arg_of_decorator): #这里是装饰器的参数
    print Arg_of_decorator
    #最终被返回的函数
    def Newdecorator (func): 
        print func return
        func return
    newdecorator


@decorator_with_params ("Deco_args"
def Foo3 (): Pass
Foo3 ()

The difference with the front is: more than the previous layer of encapsulation, the first pass parameters, and then pass the function name

The first function, Decomaker, is a decorative function, and its parameters are used to enhance the "enhanced decoration". Since this function is not a decorated function object, you must create at least one function to accept the decorated function internally, and then return the object (actually at this point foo3= decorator_with_params (arg_of_decorator) (Foo3)) With parameter adorner-packing with parameter function

def Decorator_whith_params_and_func_args (Arg_of_decorator):
    def handle_func (func):
        def Handle_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 Adorner

There are three built-in adorners: Staticmethod,classmethod, property

Class A ():
    @staticmethod
    def test_static ():
        print "Static"
    def Test_normal (self):
        print "normal" "
    @classmethod
    def test_class (CLS):
        print" Class ", cls

a = A ()
a.test_static ()
a.test_ Static ()
A.test_normal ()
A.test_class ()

Results:

static
static
normal
class __main__. A

A.test_static

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

is basically similar to a global function (no need to pass in self, only a generic argument), except that it can be invoked through an instance object of a class or class, without implicitly passing any arguments.

Static methods similar to those in static languages

B.test_normal

Normal object method: Normal object method requires at least one self parameter, representing class object instance

C.test_class

The instance method defined in the class becomes a class method

Classmethod needs to pass in class objects, which can be invoked through instances and class objects.

is a method that is related to a class that can be invoked by a classes or class instance and implicitly as the first argument by using the class object, which is not an instance object of class.

This approach may be a bit odd, but as long as you understand that Python class is also a real object in memory, rather than the type that exists in the static language only in the compile period, that's fine. The normal approach is to use a method associated with an instance object of a class, invoke it through a class instance object, and pass the instance object implicitly as the first argument, which is also similar to other languages.

D. Differences

Staticmethod,classmethod is the equivalent of a global method, typically used in an abstract class or a parent class. is generally independent of the specific class.

Class methods require an additional CLS of class variables, and when there is a subclass inheritance, the class variable that invokes the class method passes the CLS as a subclass, not as a parent class.

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

By definition, incoming arguments are not invoked the same way.

E.property

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

Class B ():
    def __init__ (self):
        Self.__prop = 1
    @property
    def prop (self):
        print "
        call get" return Self.__prop
    @prop. Setter
    def prop (self, value):
        print ' call set '
        Self.__prop = value
    @ Prop.deleter
    def prop (self):
        print "Call del"
        del Self.__prop
other

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

@a
@B
@c
def f ():

Equivalent to

f = A (B (C (f)))

The B.decorator object can be a modular method or a class method

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

Functools.wraps (func) total_ordering (CLS) go see for yourself, follow up with a simple example

A variable that controls whether the call function is statistical time

#!/usr/bin/env python
#-*-coding:utf-8-*-
# @author: wklken@yeah.net
# @version: A test of Decorator
# @date: 20121027
# @desc: Just a test


import logging from time

import time

logger = Logging.getlogger () 
  logger.setlevel (logging. DEBUG)
Is_debug = True

def count_time (is_debug):
    def  Handle_func (func):
        def  Handle_ Args (*args, **kwargs):
            if is_debug:
                begin = Time ()
                func (*args, **kwargs)
                logging.debug ("[" + Func . __name__ + "]->" + str (time ()-Begin)
            else:
                func (*args, **kwargs) return
        Handle_args return
    H Andle_func

def PR (): For
    I in range (1,1000000):
        i = i * 2
    print "Hello World"

def Test ():
    p R ()

@count_time (is_debug)
def test2 ():
    PR ()

@count_time (False)
def test3 ():
    PR ()

if __name__ = = "__main__":
    Test ()
    test2 ()
    test3 ()

Results:

Hello World
Hello World
debug:root:[test2]-> 0.0748538970947
Hello World

The end!

Wklken

Gighub:https://github.com/wklken

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

2012-10-27

Reprint please indicate the source, thank you!

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.