Differences between class and function decorator

mk mrkafk at gmail.com
Fri Jan 16 14:26:54 EST 2009


Hello everyone,

I rewrote an example someone posted here recently from:

 >>> def print_method_name(method):
	def new_meth(*args, **kwargs):
		print method.func_name
		return method(*args, **kwargs)
	return new_meth

 >>> @print_method_name
def f2():
	pass

 >>> f2()
f2


..to:

 >>> class MyMethod(object):
	def __init__(self, func):
		self.name = func.func_name
		self.func = func
	def __call__(self):
		print self.name
		return self.func

	
 >>> @MyMethod
def f():
	pass

 >>> f()
f
<function f at 0x017CDA70>

Note that function decorator returned None, while class decorator 
returned function.

Why the difference in behavior? After all, print_method_name decorator 
also returns a function (well it's a new function but still a function)?

Regards,
mk




More information about the Python-list mailing list