Python 装饰器初学笔记

  • 装饰器, 不明思议, 作用是来装饰一个东西的, 注意, 是装饰, 不是修改. 个人感觉, 就好比化妆, 只是在人本来的面貌上做了一些修饰, 并没有真正改变人的样子.

  • 下面以一个简单的案例来逐步实现装饰器:
import time

def student():
    print('print student name')

# 现在要为这样一个函数增加一个输出时间的功能, 于是我们将代码修改成下面的版本
# 版本二
def student():
    print_time()
    print('print student name')

def print_time():
    print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))

# 这种写法虽然说实现了上面的功能, 但却违背了开闭原则, 同时如果有很多个函数都需要输出时间的功能, 并且万一输出时间的函数的函数名称改变了, 那么将会很麻烦. 所以继续改

# 版本三
def student():
    print('print student name')

def print_time(func):
    print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
    func()

print_time(student)

# 这种写法仍然有逻辑上的问题, 因为打印时间这个功能是属于 student 这个函数的, 但是上面这种写法, 是在另外一个函数中写了这个功能, 并不是 student 本身的功能, 上面这种写法和下面的写法个人感觉并没有什么区别
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
student()

# 所以继续改
# 版本四
def decorator(func):
    def wrapper():
        print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
        func()
    return wrapper

def student():
    print('print student name')

f = decorator(student)
f()

# 这种写法和版本三的区别并不大, 甚至在调用的时候更加麻烦, 所以继续改
# 版本五 (语法糖)
def decorator(func):
    def wrapper():
        print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
        func()
    return wrapper

@decorator
def student():
    print('print student name')

student()

# 当 student 函数需要传递参数的时候的情况
def decorator(func):
    def wrapper(name):
        print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
        func(name)
    return wrapper

@decorator
def student(name):
    print('print student ' + name)

student('xiaosheng')

# 如果要装饰多个函数, 并且每个函数的参数都不一样, 那么代码如下
def decorator(func):
    def wrapper(*args):
        print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
        func(*args)
    return wrapper

@decorator
def student(name):
    print('print student ' + name)

student('xiaosheng')
本作品采用《CC 协议》,转载必须注明作者和本文链接
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!