装饰器是什么呢?
我们先来打一个比方,我写了一个python的插件
提供给用户使用,但是在使用的过程中我添加了一些
功能,可是又不希望用户改变调用方式,那么该怎么
办呢?
这个时候就用到装饰器假如我们有一个home函数如下:
def home():
print' this is the home page!'
而我们希望用户在访问home 函数之前先验证一下权限,那么在
用户不改变调用方法的情况下,就需要在home 中 调用一个
login函数,
def login (usr):
if uer =='eva_j':
return True
def home():
result =login()
if fesult:
print' this is the home page!'
这样 可以实现我们的需求,但是我们看到 home 的代码发生了很大的变化,所有的代码都要被包裹在一个if 语句中,并且要进行缩进,这往往不是我们希望看到的,那么我们还可以怎么做呢>?
def home():
print'this is the home page!'
print home
输出:<function home at 0x0000000000219c978>
我们定义了一个home函数,但是并不使用home()调用它 而是让程序打印出home方法的地址。
那么我们再看这段代码:
def login(usr):
if uer == ‘eva_j’:
return True
def wrapper (funcanme):
if login (eva_j):
return funcname
def home():
print 'this is the home page!'
home=wrapper (home)
home()
输出的结果:this is 。sssssssssssss