python--Decorator Basics

Source: Internet
Author: User
Tags class definition function definition

Adorner Basics

The previous quick introduction to the adorner syntax, here, we will go deep inside the adorner working mechanism, more detailed and systematic introduction of the content of the adorner, and learn to write their own new adorners more advanced syntax.

=================================================================================

What is an adorner?
Decorations are a way of specifying management code for functions and classes. The Python adorner is presented in two forms:
The "1" function decorator makes name rebinding at the time of function definition, providing a logical layer to manage functions and methods or subsequent calls to them.
The "2" class decorator makes name rebinding at the time of class definition, provides a logical layer to manage classes, or manages subsequent calls to the instances that they create.
In short, adorners provide a way to insert Autorun code at the end of a function and class definition statement-for a function adorner, at the end of a Def, and for a class decorator, at the end of classes. Such code can play a different role.
Adorners provide a bit of code maintainability and aesthetic relevance. In addition, as a structured tool, adorners naturally promote code encapsulation, which reduces redundancy and makes the future easier.

=================================================================================

function Adorner
The initial function name is re-bound to the result by running another function at the end of a function's def statement.

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

Usage
The adorner is written next to the DEF statement that defines a function or method, and it consists of the @ symbol and a reference to the META function immediately following it-a function (or other callable object) that manages another function.
On the encoding, the function adorner automatically follows the following syntax:

@decoratordef F (ARG): ... F (99)
map to this equivalent form:

def F (ARG): ... f = decorator (f) F (99)
The adorner here is a single-parameter callable object that returns a callable object with the same number of arguments as F.
When the F function is subsequently called, it automatically invokes the object returned by the adorner.

In other words, the decoration actually maps the first line below to the second row (although the adorner runs only once during decoration)
Fun (6,7) Decorator (func) (6,7)
This automatic name re-binding also explains the previous static method and the reason for the property adorner syntax:
Class C: @staticmethoddef Meth (...): ... @propertydef name (self): ...
----------------------------------------------------------------------------------------------------------- -----------------------------------
Realize
The adorner itself is a callable object that returns a callable object. In fact, it can be any type of callable object and return any type of callable object: any combination of functions and classes can be used, although some combinations are more appropriate for a particular background.

There is a common coding pattern-the adorner returns a wrapper that keeps the initial function in a closed scope:
def decorator (f):d EF Wrapper (*args): # Use F and *args# to call the original F (*args) return wrapper@decoratordef func (x, y): ... func (6,7)
when the name Func is called later, it does invoke the wrapper function returned by the adorner, and then the wrapper function may run the initial func because it is still available in a closed scope.

To do the same thing for a class, we can overload the invoke operation:
Class Decorator:def __init__ (self,func): Self.func = Funcdef __call__ (Self,*args): # using Self.func and args# Self.func (*args) Call the original func@decoratordef func (x, y): func (6,7)
However, it is important to note that, in class-based code, it is valid for intercepting simple functions, but when applied to a class method function, it is not very effective:
The following is a counter example:
Class Decorator:def __init__ (self,func): Self.func = Funcdef __call__ (self,*args): # call Self.func (*args) failed, Because the C instance parameter cannot be passed class C: @decoratordef Method (Self,x,y): ...
The problem with decorating the method of binding to a class method instead of a simple function is that when the adorner's method __call__ subsequently runs, the self of the decorator takes an instance of the adorner class, and the instance of Class C is not included in a *args.

In this case, the workaround for nested functions works better:
def decorator:def Warpper (*args): # ... return wrapper@decoratordef func (x, y):. Func (6,7) class C: @decoratordef Method ( Self,x,y): ... x = C () x.method (6,7)
=================================================================================

Class Decorator

The class adorner uses the same syntax and very similar encoding as the function adorner. A class adorner is a way of managing a class, or wrapping an instance build call with extra logic to manage or extend the instance created by the class.
--------------------------------------------------------------------------------------------------------------- -------------------------------

Usage
Suppose the class adorner returns a single-argument function for a callable object, with the class adorner's syntax :

@decoratorclass c:...x = C (99)
Equivalent to the following syntax:

Class C: ... c = Decorator (c) x = C (99)
The direct effect is that subsequent invocation of the class name creates an instance that triggers the callable object returned by the adorner, rather than invoking the original class itself.
--------------------------------------------------------------------------------------------------------------- -------------------------------

Realize
The class adorner returns a callable object that typically creates and returns a new instance of the original class, in some way extending the management of its interface. For example, the following instance inserts an object to intercept an undefined property of a class instance:

def decorator (CLS): Class Wrapper:def __init__ (Self,*args): self.wrapped = CLS (*args) def __getattr__ (self,name): return GetAttr (self.wrapped,name) return wrapper@decoratorclass c:# C = Decorator (C) def __init__ (self,x,y): # Run by wrapper.__ init__self.attr = ' spam ' x = C (6,7) # equivalent to wrapper (6,7) print (x.attr)
In this example, the adorner re-binds the name of the class to another class, which maintains the original class in a closed scope.

Like a function decorator, a class adorner can often be written as a "factory" function that creates and returns a callable object.
=================================================================================

Adorner nesting
Sometimes, an adorner is not enough, the adorner syntax allows us to add multiple layers of wrapper logic to a function or method of an adorner. The syntax for this form of adorner is :

@a@b@cdef f (...): ...
this translates as follows:
def f (...): ... f = A (B (C (f)))
Here, the initial function is passed through 3 different adorners, each of which processes the previous result.
=================================================================================

Adorner parameters
Both the function adorner and the class adorner can accept parameters, as follows:

@decorator (A, b) def F (ARG): ... F (99)
automatically mapped to its equivalent form:
def F (ARG): ... F = Decorator (A, B) (f) F (99)
adorner parameters are parsed before decorating, and they are often used to hold state information for subsequent calls. For example, the adorner function in this example might take the following form:
def decorator (A, B): # Save or use a and bdef actualdecorator (F): # Save or use the function F # Returns a callable object return Callablereturn Actualdecorator

=================================================================================

above, this is the basic knowledge of adorners, Next will learn to write their own adorners

python--Decorator Basics

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.