15. Decorators in Python

  • A decorator is a simple way to increase the functionality of a function or class, it can insert the same functionality into different functions or classes;
  • The expression syntax of decorators is implemented using the special symbol "@";
  • The definition of a decorator is exactly the same as that of an ordinary function, except that the parameters of the decorated function must have functions or objects.

1. Decorative function

The general form of a decorator decorator function is as follows:

# 定义修饰器
def decorater(fun):
    def new_fun(*args, **kwargs):
        <语句1>
        fun(*args, **kwargs)
        <语句2>
    return new_fun

#调用修饰器
@decorater
def function():
    pass

Example of decorated function:

#定义装饰器
def myDecorator(fun):
    def wrapper(*args, **kwargs):
        print('Start...')
        fun(*args, **kwargs)
        print('End...')

    return wrapper

@myDecorator
def useDecorator1(x):
    result = x * 2
    print(result)

@myDecorator
def useDecorator2(name):
    print('Hello', name)

if __name__ == '__main__':
    useDecorator1(3)
    useDecorator1('Python')

Running result:
Start…
6
End…
Start…
PythonPython
End…


2. Decorative

Decorators can decorate not only functions but also classes. The method used by the decorator to define the decorated class is to define the function of the nested class and return the new class.

Decorative class example:

# 定义修饰类
def myClassDecorator(objClass):
    class MyClassDecorator:
        def __init__(self, z = 0):
            self.__z = z
            self.wrapper = objClass()

        def postion(self):
            self.wrapper.postion()
            print('z axis:', self.__z)

        def setPostion(self, x, y, z):
            self.wrapper.setPostion(x, y)
            self.__z = z

    return MyClassDecorator

@myClassDecorator
class Cooridination:
    def __init__(self, x = 2, y = 9):
        self.__x = x
        self.__y = y

    def postion(self):
        print('x axis:', self.__x)
        print('y axis:', self.__y)

    def setPostion(self, x, y):
        self.__x = x
        self.__y = y

if __name__ == '__main__':
    coor = Cooridination()
    coor.postion()
    print()
    coor.setPostion(10, 20, 30)
    coor.postion()

Running result:
x axis: 2
y axis: 9
z axis: 0

x axis: 10
y axis: 20
z axis: 30

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325588763&siteId=291194637