should be no such reverse relationship)
The second type:
Copy Code code as follows:
@a (args)
def f ():
This form is the decorator with the parameters of the formulation. Then Python will handle it as:
Copy Code code as follows:
def f ():
_deco = A (args)
f = _deco (f)
As you can see, Python first execute
Python decorator implements several types of verification functions, such as python
A new requirement comes recently. We need to add several resource permissions to the system. Minimize code changes and program complexity. Therefore, it is more scientific to use the decorator.
Some existing
1. Decorative Device
A syntax format that is used to replace another coding style, a syntactic sugar that clearly identifies such a grammar through a grammatical structure.
Automatically executes code at the end of a decorated object (code that needs to be explicitly stated when not using adorner syntax)
A decorated object can be a function, a class, a decorated object as a function (the adorner is defined as a function adorner), a de
num is 1,aa is 25.000000the num is 1,val is 50.000000
2. return in recursion:
def divide(n,val): n += 1 print(val) if val / 2 > 1: aa = divide(n,val/2) print('the num is %d,aa is %f' % (n,aa)) return(aa) print('the num is %d,val is %f' % (n,val)) return(val)divide(0,50.0)
Result description ):
50.025.012.56.253.1251.5625the num is 6,val is 1.562500the num is 5,aa is 1.562500the num is 4,aa is 1.562500the num is 3,aa is 1.562500the num is 2,aa is 1.562500the num is 1,aa is 1.562500
module decoration function, we can find that the code with decorator decoration function is more concise and understandable, but they are more efficient to execute? Below we test by the timer:From Timeit import timerprint Timer (' Add ', setup= ' from __main__ import add '). Timeit (100000) #将该段代码 added in the previous example # This prints the time it ran 100,000 times.Functools.wraps Decoration Execution Result:2.37299322602Decorator module Decorat
Package-easy to understand
class function_wrapper(object): def __init__(self, wrapped): self.wrapped = wrapped def __call__(self, *args, **kwargs): return self.wrapped(*args, **kwargs) @function_wrapper def function(): pass
Function introspection
When talking about a function, we usually want its attributes to be clearly defined as described in the document, such as _ name _ and _ doc __.
The attributes of a function are c
add, so as to ensure that the function is not changed by the method of the call unchanged. There is a more elegant way to replace the 12th line of statements in the Python syntax. As follows:
1 #装饰器 2 def Decorator (func): 3 def warpper (): 4 print ("The result of 1+2 is:") 5 func () 6 return Warpper 7
In front of the decoration function directly with "@xxx" (XXX for the adorner
fact, there are two other optional parameters. Attribute names in assigned are replaced by values, while attribute names in updated are merged by update, you can obtain the default values by viewing the source code of functools. For this decorator, it is equivalent to wrapper = functools. wraps (func) (wrapper ).
2.3.2. total_ordering (cls ):
This decorator is useful in specific scenarios, but it is added
An adorner (decorator) is an advanced Python syntax. Adorners can be used to process a function, method, or class. In Python, we have several methods for working with functions and classes, such as in Python closures, where we see the function object as the result of a funct
Function decorator of Python)
Apply multiple decoration methods to one method:@
@ B
@ C
Def F ():
# It is equivalent to the following form. Python calls the decoration method in sequence according to the application order (the last one is called first)
Def F ():
F = A (B (C (F )))
Decoration method analysis:
Each decorator
means that we can declare functions within a function and all scopes and claim-cycle rules also apply.
>>> def outer (): ... x = 1 ... def inner (): ... Print x # 1 ... Inner () # 2...>>> outer () 1
This looks slightly more complex, but its behavior is still fairly straightforward and easy to understand. Think about what happened in # # # # # # # # # # # # # # # # # # # # # #--python Looking for a local variable named X, failed, then searc
Examples of python function decorator usage and python function examples
This document describes how to use the python function decorator. Share it with you for your reference. The details are as follows:
The decorator is often us
Python-Day4 Python basics advanced Builder/iterator/decorator/Json pickle data serialization, python-day4jsonI. Generator
By using the list generation method, we can directly create a list. However, due to memory restrictions, the list capacity must be limited. In addition, creating a list containing 1 million element
Analyze the key points of the Decorator pattern in the Python design pattern, pythondecorator
First, a four-person group defines the Decorator mode: dynamically adds some additional responsibilities to an object.Let's talk about the advantages of this mode: authentication, permission check, logging, checking parameters, locking, and so on. These functions are irr
. The decorator can solve this problem and retain the special attributes of the decorated functions.? 123456789101112131415161718 import timeimport functools def timeit (func): @ functools. wraps (func) def wrapper (): start = time. clock () func () end = time. clock () print 'used: ', end-start return wrapper @ timeitdef foo (): print 'in foo () 'foo () print foo. _ name _ first, pay attention to the 5th rows. If you comment this line, foo. _ name _
Python function Summary-decorator and lambdaThis article is still a learning note. The structure of this article first talks about the decorator and then lambda expressions. The decorator has many contents. First, the decorator syntax is briefly introduced, and then the deta
extra stuff}}//decorator can add his or her own behavior before or after the act of the delegate to achieve a specific purpose public class Decoratordemo {public static void Ma In (string[] args) {//8. Client have the responsibility to compose desired configurations Widget awidget = new Borderdecorator ( New Borderdecorator (New Scrolldecorator (New Textfie LD (80, 24))); Awi
the decorated function in the closure, returns a new function object.Note: decorator does not have to appear in the form of a function. it can be any object that can be called. for example, it can also appear in the form of a class. See the example in this article.When the decorator function is called externally, the syntactic sugar of the
Oh! As a teacher who teaches Python, I find that it is very difficult for the students to get to the Python decorator at first, perhaps because the adorner is really hard to understand. Decorating the decorator requires you to understand some of the concepts of functional programming and, of course, to understand some
service a little change to simplify processing, we can be used in accordance with their own circumstances of the cache processing and log processing. In the specific operation of the careful friend may find in the configuration file in the order of the appearance of different services to determine the order of execution of two services, that is, the spring AOP to perform the cut-in action is done through the decorator mode, using a similar stack of a
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.