Python Decorators

It is a way to run extra processing steps at function and class definition time with explicit syntax. It comes in two flavors:

  • Function decorators—the initial entry in this set. They specify special operation modes for both simple functions and clesses’s methods by wrapping them in an extra layer of logic implemented as another function, usually called metafunction.
  • Class decorators—a later extension. They do the same for classes, adding support for management of whole objects and their interfaces. Though perhaps simpler, they often overlap in roles with metaclasses.

A First Look at User-Defined Function Decorators

>>> class Tracer(object):
	def __init__(self, func):
		self.counter = 0
		self.func = func
	def __call__(self, *args,**kwargs):
		self.counter += 1
		print("call func:%s times:%d" % (self.func.__name__, self.counter))
		return self.func(*args, **kwargs)

	
>>> @Tracer
def add(x, y):
	return x + y

>>> add(1, 1)
call func:add times:1
2
>>> add(2, 2)
call func:add times:2
4
>>> 
posted @ 2015-10-28 15:53  hotbaby  阅读(173)  评论(0编辑  收藏  举报