简体   繁体   中英

How can I pass all the parameters to a decorator?

I tried to trace the execution of some methods using a decorator. Here is the decorator code:

def trace(func):
    def ofunc(*args):
        func_name = func.__name__       
        xargs = args        
        print "entering %s with args %s" % (func_name,xargs)
        ret_val = func(args)
        print "return value %s" % ret_val
        print "exiting %s" % (func_name)
    return ofunc 

The thing is, if I try to apply this decorator to methods, the self parameter doesn't get sent. Can you tell me why, and how can I fix that?

This line is incorrect:

ret_val = func(args)

You're forgetting to expand the argument list when you're passing it on. It should be:

ret_val = func(*args)

Sample output with this modification in place:

>>> class Test2:
...     @trace
...     def test3(self, a, b):
...        pass
... 
>>> t = Test2()
>>> t.test3(1,2)
entering test3 with args (<__main__.Test2 instance at 0x7ff2b42c>, 1, 2)
return value None
exiting test3
>>> 

If you ever expand your decorator to also take keyword arguments, you'd also need to expand those appropriately when passing them on, using ** .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM