- 装饰器, 不明思议, 作用是来装饰一个东西的, 注意, 是装饰, 不是修改. 个人感觉, 就好比化妆, 只是在人本来的面貌上做了一些修饰, 并没有真正改变人的样子.
- 下面以一个简单的案例来逐步实现装饰器:
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)
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()
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')