在学习cs20si中遇到了装饰器,所以这里介绍下装饰器decorator的使用。
主要内容依据http://blog.apcelent.com/python-decorator-tutorial-with-example.html
Python中,所有的东西都是对象,一个函数可以被赋到变量中,传递给另一个函数,或者被其他函数作为返回值。
Python的装饰器就是一个函数,接受函数作为参数,并且用另一个函数作返回值。
import time
def timetest(input_func):
def timed(*args, **kwargs):
""" caculate time"""
start_time = time.time()
result = input_func(*args, **kwargs)
end_time = time.time()
print "Method Name - {0}, Args - {1}, Kwargs - {2}, Excution Time - {3}".format(
input_func.__name__,
args,
kwargs,
end_time - start_time
)
return result
return timed
@timetest
def foorbar(*args, **kwargs):
time.sleep(0.3)
print "inside foorbar"
print args, kwargs
foorbar(["hello world"], foo=2, bar=5)
将函数foorbar传递给了装饰器timetest,作为参数input_func
method装饰器可以将类的method作为类的属性
def method_decorator(method):
def inner(city_instance):
if city_instance.name == "SFO":
print "Its a cool place to live in."
else:
method(city_instance)
return inner
class City():
def __init__(self, name):
self.name = name
@method_decorator
def print_test(self):
print self.name
p1 = City("SFO")
p1.print_test()
输出
Its a cool place to live in.
p1 = City("SF")
p1.print_test()
输出
SF
如何想要返回值为函数时,可以采用function 装饰器,但如果希望装饰器的返回值为一个对象时,需要用一个class decorator。
class decoclass():
def __init__(self, f):
self.f = f
def __call__(self):
# before f actions
print 'decorator initialised'
self.f()
print "decorator terminated"
# after f actions
@decoclass
def kclass():
print "class"
kclass()
输出
decorator initialised
class
decorator terminated