方法的参数没有传递给装饰器

时间:2013-11-01 22:04:13

标签: python decorator

嘿,我有一个定义如下的方法:

from x.y import util
class my_Class(some_object):
    @util.myDecorator
    def foo(self, log_file):
    '''
    Test that search entered into the search bar is the search being
    executed in the job.
    '''
    self.some_page.open()
    textarea = self.some_page.searchbar

    searchbar.run_search(log_file.search_string)
    self.browser.capture_screenshot()
    self.some_page.jobstatus.wait_for_job_complete()

    self.verify_equals(
        self.some_page.jobstatus.event_count,
        log_file.event_count,
        "Event count doesn't seem to be right.")

装饰器位于文件util.py

def mydecorator(func):
    def timeit(*args, **kwargs):
        start_time = time.time()
        ret=func(*args, **kwargs)
        end_time = time.time()
        print end_time - start_time
        return ret
    return timeit

当我尝试执行代码时,它在ret=func(*args, **kwargs)失败并显示错误消息

  

TypeError:foo()只需要2个参数(给定1个)

  • 我打印了* args的内容(带','.join(str(each) for each in args))以查看其中包含的内容,并将其打印出来
  

< .... my_Class对象at ...>

装饰器适用于只有一个arg(self)的方法。我在这里错过了什么吗?

1 个答案:

答案 0 :(得分:0)

你回答评论,请注意它有效:

>>> import time
>>>
>>> def mydecorator(func):
...     def timeit(*args, **kwargs):
...         start_time = time.time()
...         ret=func(*args, **kwargs)
...         end_time = time.time()
...         print end_time - start_time
...         return ret
...     return timeit
...
>>> class my_Class(object):
...     @mydecorator
...     def foo(self, arg_1):
...         print arg_1
...
>>> my_Class().foo(100)
100
0.0