Adorner advanced

Now? , We've learned how decorators work . Next , We still have a lot to figure out . such as : Functions with parameters 、 Multiple decorators decorate a function at the same time 、 Decorators and class decorators with parameters .

Decoration belt parameter function

def foo(func): # The parameter received is a function name 
def bar(x, y): # Here you need to define the same parameters as the decorated function
print(" Here are the new features ...") # new function
func(x, y) # Decorated function name and parameters have , You can execute the decorated function
return bar # Define a function that takes two arguments
def f1(x, y):
print("{}+{}={}".format(x, y, x+y)) # Call decorated function
f1(100, 200)

Output :

 Here are the new features ...

Multiple decorators

def foo1(func):
print("d1") def inner1():
return "<i>{}</i>".format(func()) return inner1 def foo2(func):
print("d2") def inner2():
return "<b>{}</b>".format(func()) return inner2 @foo1
def f1():
return "Hello Andy" # f1 = foo2(f1) ==> print("d2") ==> f1 = inner2
# f1 = foo1(f1) ==> print("d1") ==> f1 = foo1(inner2) ==> inner1 ret = f1() # call f1() ==> inner1() ==> <i>inner2()</i> ==> <i><b>inner1()</b></i> ==> <i><b>Hello Andy</b></i>

With parameter decorator

Decorated functions can take arguments , Decorators can also have parameters .

Looking back at the ornaments that we wrote on them , They default to the decorated function as the only parameter . But what? , Sometimes we need to pass parameters to our decorator , What should we do in this situation ?

Next , We will implement the decorator with parameters step by step :

First, let's review the code above :

def f1(func): # f1 Is the decorator function we define ,func It's a decorated function 
def f2(*arg, **kwargs): # *args and **kwargs Is the parameter of the decorated function
func(*arg, **kwargs)
return f2

From the code above , What we found ?

If my decorator has parameters , There's no place to write … What shall I do? ?

Or do you want to use a closure function !

We need to know , Functions can be nested in two layers , More layers can be nested :

# Three layer nested function 1
def f1():
def f2():
name = "Andy"
def f3():
return f3
return f2

Function calls after nesting three layers :

f = f1() # f --> f2
ff = f() # ff --> f3
ff() # ff() --> f3() --> print(name) --> Andy

Be careful : In the inner function f3 You can access its outer functions in f2 Variables defined in , Of course, you can also access its outermost functions f1 Variables defined in .

# Three layer nested function 2
def f1():
name = "Andy"
def f2():
def f3():
return f3
return f2

call :

f = f1() # f --> f2
ff = f() # ff --> f3
ff() # ff() --> f3() --> print(name) --> Andy

Okay , Now we can implement our decorator function with parameters :

# Decorators with parameters need to define a three-tier nested function 
def d(name): # d Is the newly added outermost function , Pass parameters to our original decorator ,name That's the function we're going to pass
def f1(func): # f1 It's our original decorator function ,func It's a decorated function
def f2(*arg, **kwargs): # f2 Is an internal function ,*args and **kwargs Is the parameter of the decorated function
print(name) # Use the arguments of the decorator function
func(*arg, **kwargs) # Call the decorated function
return f2
return f1

The above is a code example of decorator with parameters , Now let's write a complete application :

def d(a=None): # Define an outer function , Pass parameters to decorator --role
def foo(func): # foo It's our original decorator function ,func It's a decorated function
def bar(*args, **kwargs): # args and kwargs Is an argument to the decorator function
# Make some logical judgments according to the parameters of the decorator
if a:
print(" Welcome to {} page .".format(a))
print(" Welcome to the home page .")
# Call the decorated function , Receiving parameters args and kwargs
func(*args, **kwargs)
return bar
return foo @d() # Don't pass parameters to decorator , Use default 'None' Parameters
def index(name):
print("Hello {}.".format(name)) @d(" The movie ") # Send a message to the decorator ' The movie ' Parameters
def movie(name):
print("Hello {}.".format(name)) if __name__ == '__main__':

Output :

 Welcome to the home page .
Hello Andy.
Welcome to the movie page .
Hello Andy.

Class decorator and decoration class

Class decorator

Besides decorating functions with functions , We can also use classes to decorate functions .

class D(object):
def __init__(self, a=None):
self.a = a
self.mode = " decorate " def __call__(self, *args, **kwargs):
if self.mode == " decorate ":
self.func = args[0] # By default, the first parameter is the decorated function
self.mode = " call "
return self
# When self.mode == " call " when , Execute the following code ( That is, when a function decorated with a class is called )
if self.a:
print(" Welcome to {} page .".format(self.a))
print(" Welcome to the home page .")
self.func(*args, **kwargs) @D()
def index(name):
print("Hello {}.".format(name)) @D(" The movie ")
def movie(name):
print("Hello {}.".format(name)) if __name__ == '__main__':


All of our examples above are just a function , Returns an executable function .Python In addition to decorating functions, decorators in , It can also be used for decoration .

You can use decorators , To batch modify some methods of the decorated class :

# Define a class decorator 
class D(object):
def __call__(self, cls):
class Inner(cls):
# Override the f Method
def f(self):
print("Hello Andy.")
return Inner @D()
class C(object): # The decorated class
# There is an example method
def f(self):
print("Hello world.") if __name__ == '__main__':
c = C()

Python More related articles on decorator advancement

  1. ( turn )python Adorner advanced 1

    Python One of the advanced decorations Look at the example There are many articles about decorators on the Internet , For a long time, I didn't let people understand what adorner is , What's the use , Let's go straight to a few examples . Python Recursively find the Fibonacci sequence def fibonacc ...

  2. ( turn )python Ornament 2

    Python The second advanced decoration Save metadata for decorated methods What is metadata for methods Take a chestnut def hello(): print('Hello, World.') print(dir(hello)) give the result as follows : ...

  3. Python function -- Adorner advanced

    Open and closed principle 1. Open to expansion Why open to expansion ? We said , Any program , It's impossible to have all the functions in mind at the beginning of the design without any update or modification in the future . So we have to allow code extensions . Add new features . 2. It's a good idea to modify ...

  4. day 12 - 1 Adorner advanced

    Adorner advanced A brief review of decorators Principles of decorator development : The principle of opening and closing is the function of decorator : Without changing the calling mode of the original function , The essence of adding function decorators before and after functions : Closure function Patterns of decorators def wrapper(func): ...

  5. Python— Detailed explanation of ornaments

    Decorator :( Grammatical sugar ) The essence is function , It gives function new functions , But it doesn't change the source code and calling method of the function   principle : 1. The source code of the decorated function cannot be modified 2. You can't change the way the decorated function is called 3. The return value of the function is also unchanged These two points are simple ...

  6. day4 Advanced decoration 、 Generator iterator

    Adorner advanced Parameter decorator # A certain situation # 500 A function decorator , I don't want to add this decorator after adding it , Another quarter , I want to add it again # You can design your decorators , To confirm whether it is implemented or not # Case one # to want to 500 A function ...

  7. Learn... In five minutes Python Decorator , No more panic after the interview

    This article is originated from the official account :TechFlow, Originality is not easy. , Ask for attention It's today Python Topic No 12 An article , Let's see Python Decorator . A piece of embarrassment About five years ago, during the interview , I've learned the importance of it . At that time, I Pyt ...

  8. Python Decorator pit filling guide | The most common error messages 、 Causes and solutions

    This article is a study note for students of Hogwarts Testing Institute . Python About decorators Decorator (Decorator) yes Python A very practical grammatical sugar function . Decorators are essentially functions that return values as well as functions , It can be called “ Function of function ”. ...

  9. About python Decorator

    About python Decorator , It's not a systematic introduction , Just a few questions 1 First of all, it's very important to understand the effect of variables on 2 Second, we need to understand closures def logger(func): def inner(*args, **kwargs) ...

Random recommendation

  1. ( turn )c The pointer

    from : It's been two days BREW 了 , It's using C The grammar of . I learned it at school C They're all learning ...

  2. Tkinter Tutorial of Button piece (2)

    Reprinted from : # Tkinter Tutorial of Button piece (2)'''5. Appoint Button The width and height of ...

  3. WisDom.Net framework design ( 8、 ... and ) Persistence layer

    WisDom.Net --- Persistence layer   1. What is the persistence layer         The persistence layer is responsible for the most basic functional support , Provide a high level for the project , Unified , And concurrent data persistence mechanism , Provides, for example, the establishment of a database connection , Close database connection , perform sql language ...

  4. [OC note ] static keyword

    Add the static keyword , You can make a local variable retain the value of multiple method calls . When multiple methods operate on a static variable , Multiple methods share the value of the same static variable .

  5. memcached Practical series ( 6、 ... and ) understand Memcached Data storage mode of

    Memcached The way in which data is stored is called Slab Allocator, The basic way is : 1: First, divide the memory into many parts Slab, This size is predetermined , To solve the problem of memory fragmentation . I don't know how to configure the startup parameters, so I can refer to it ...

  6. Future FutrueTask Callable Class source code description and principle use

    1.Future Callable FutureTask Source code description JDK Built in Future Mainly used to Callable Interface and FutureTask class . Callable Is similar to the Runnable The interface of , ...

  7. php Print

    function preview() { bdhtml = window.document.body.innerHTML; sprnstr = "<!--startprint--> ...

  8. Unity3D note Angry birds &lt; 5、 ... and &gt; Bird animation +Unity3D How to set breakpoint mode

    Preface : Animation of birds , Before I make complaints about it js Write U3D, It's changed to C# To write , I didn't expect to have a problem . To achieve the effect of using UnityEngine; using System.Collections; /// < ...

  9. log4j:WARN No appenders could be found for logger (org.apache.hadoop.metrics2.lib.MutableMetricsFactory). log4j:WARN Please initialize the log4j system properly. log4j:WARN See http://logging.apache.o

    The above error report is local java debugging (windows) hadoop colony The emergence of Solution : stay resources Create a file under the folder In fact hadoop Install under directory e ...

  10. centos Compilation and installation php7

    Environmental statement VMware 12 Set up in CentOS 7 x64 4 nucleus 2G Memory Is already installed in the environment ...