看一个例子:
def require_int (func):
def wrapper (arg):
assert isinstance(arg, int)
return func(arg)
return wrapper
@require_int
def p1 (arg):
print arg
其中@require_int就是一个函数修饰符了,本质上函数修饰符就是一个函数,只是对定义在它下面的函数进行一次修改,如上面的例子,应用函数修饰符原理是这么执行的:
p1 = require_int(p1)
这里这个修饰符的功能是检查函数的参数类型是否为整数
更高级一点是函数修饰符可以也可以带参数的,看下面这个例子:
def synchronized(lock):
""" Synchronization decorator. """
def wrap(f):
def newFunction(*args, **kw):
lock.acquire()
try:
return f(*args, **kw)
finally:
lock.release()
return newFunction
return wrap
if __name__ == '__main__':
from threading import Thread, Lock
import time
import os
myLock = Lock()
class MyThread(Thread):
def __init__(self, n):
Thread.__init__(self)
self.n = n
@synchronized(myLock)
def run(self):
""" Print out some stuff.
The method sleeps for a second each iteration. If another thread
were running, it would execute then.
But since the only active threads are all synchronized on the same
lock, no other thread will run.
"""
for i in range(5):
print 'Thread %d: Start %d...' % (self.n, i),
time.sleep(1)
print '...Thread %d: Stop [%d].' % (self.n, i)
threads = [MyThread(i) for i in range(2)]
for t in threads:
t.start()
for t in threads:
t.join()
os.system("PAUSE")
这里他的原理上是这么执行的:
temp = synchronized(lock)
run = temp(run)
没有评论:
发表评论