深入了解装饰器Decorators in python

  • Decorator

    A decorator is a function that takees another function and extends the behavior of the latter function without explicitly modifying it.

  • Functions

    A function returns a value based on the given arguments.

  • First-Class Objects

    In Python, functions are first-class objects.

    This means that functions can be passed around and used as arguments, just like any other object (sting, int, float, list, and so on).

  • Inner Functions

    Inner functions are functions defined inside other functions.

  • Returning Functions From Functions

    Python also allows to use functions as return values.

    The return function without the parentheses, which means you are returning a reference to the function which returned.

  • Simple Decorators

    def my_decorator(func):
        def wrapper():
            print("Something is happening before the function is called.")
            func()
            print("Something is happening after the function is called.")
        return wrapper
    
    def say_whee():
        print("Whee!")
    
    say_whee = my_decorator(say_whee)
    

    Decorators wrap a function, modifying its behavior.

  • Syntactic Sugar

    The above format is a little clunky.

    Python allows you to use decorators in a simpler way with the @ symbol, sometimes called the “pie” syntax.

    The following example does the exact same thing as the first decorator example:

    def my_decorator(func):
        def wrapper():
            print("Something is happening before the function is called.")
            func()
            print("Something is happening after the function is called.")
        return wrapper
    
    @my_decorator
    def say_whee():
        print('Whee!')
    
  • Reusing Decorators

    A decorator is just a regular Python function.

    It can be imported into other files.

    def do_twice(func):
        def wrapper_do_twice(*args, **kwargs):  # 输入参数
            func(*args, **kwargs)
            return func(*args, **kwargs)   # return values
        return wrapper_do_twice 
    

    For information keeping by introspection:

    import functools
    
    def do_twice(func):
        @functools.wraps(func)   # 
        def wrapper_do_twice(*args, **kwargs):
            func(*args, **kwargs)
            return func(*args, **kwargs)
        return wrapper_do_twice
    
  • Fancy Decorators

  • Decorating Classes

    Decorators that are built-ins in Python are @classmethod, @staticmethod, and @property.

    The @classmethod and @staticmethod decorators are used to define methods insdie a class.

    The @property decorator is used to customize getters and setters for class attributes.

  • From 廖雪峰

    decorator本质上就是一个返回函数的高阶函数。

  • References

  1. Primer on Python Decorators
  2. PEP 318 – Decorators for Functions and Methods
  3. Python wiki : Decorators
  4. 廖雪峰的官方网站

你可能感兴趣的:(#,小白学Python,decorator,装饰器)