15、Python中的装饰器

  • 装饰器是一种增加函数或类功能的简单方法,它可以给不同的函数或类插入相同的功能;
  • 装饰器的表示语法使用特殊符号“@”来实现的;
  • 装饰器的定义与普通函数的定义完全一致,只不过装饰函数的参数必须有函数或对象。

1、装饰函数

装饰器装饰函数的一般形式如下:

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

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

装饰函数示例:

#定义装饰器
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')

运行结果:
Start…
6
End…
Start…
PythonPython
End…


2、装饰类

装饰器不仅可以装饰函数,也可以装饰类。定义装饰类的装饰器采用的方法是:定义内嵌类的函数,并返回新类。

装饰类示例:

# 定义修饰类
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()

运行结果:
x axis: 2
y axis: 9
z axis: 0

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

猜你喜欢

转载自blog.csdn.net/douzhq/article/details/79342658
今日推荐