【发布时间】:2019-01-25 09:59:56
【问题描述】:
我有一个 Timer 装饰器,它在屏幕上打印 Memoize 装饰功能的经过时间。但是,装饰器打印语句将 memoize 类打印为屏幕上的函数名称,而不是 memoize 的函数输入。例如,使用以下代码:
from memoization import Memoize
import time
import logging
from timer import Timer
@Timer
@Memoize
def pass_and_square_time(seconds):
time.sleep(seconds)
return seconds**2
def main():
logging.getLogger().setLevel(logging.ERROR)
print '\nFor pass_and_square_time({30}):'.format(n=num)
print '\n\tThe initial call of pass_and_square_time(30) yields: {ret}'.format(ret=pass_and_square_time(30))
print '\n\tThe second call of pass_and_square_time(30) yields: {ret}'.format(ret=pass_and_square_time(30))
返回以下内容:
For pass_and_square_time(30):
Timer Time Elapsed: 30.0 seconds
<memoization.Memoize object at 0x02E5BBD0> 30.0 seconds
The initial call of pass_and_square_time(30) yields: 900
Timer Time Elapsed: 0.0 seconds
<memoization.Memoize object at 0x02E5BBD0> 0.0 seconds
The second call of pass_and_square_time(30) yields: 900
当我希望 memoization.Memoize 成为 pass_and_square_time 时。我尝试了self.__wrapper__、functools.wraps 和functools.update_wrapper() 的各种不同组合,但均无济于事。
我的 Timer 类实现如下:
class Timer(object):
def __init__(self, fcn=None, timer_name='Timer'):
self._start_time = None
self._last_timer_result = None
self._display = 'seconds'
self._fcn = fcn
self._timer_name = timer_name
def __call__(self, *args):
self.start()
fcn_res = self._fcn(*args)
self.end()
print '\n\t{func} {time} seconds'.format(func=self._fcn, time=self.last_timer_result)
return fcn_res
def __get__(self, obj, objtype):
return partial(self.__call__, obj)
'''
start(), end(), and last_timer_result functions/properties implemented
below in order to set the start_time, set the end_time and calculate the
last_timer_result, and return the last_timer_result. I can include more
if you need it. I didn't include it just because I didn't want to make
the post too long
'''
我的 Memoize 类实现如下:
from functools import update_wrapper, partial
class Memoize(object):
def __init__(self, fcn):
self._fcn = fcn
self._memo = {}
update_wrapper(self, fcn)
def __call__(self, *args):
if args not in self._memo:
self._memo[args] = self._fcn(*args)
return self._memo[args]
def __get__(self, obj, objtype):
return partial(self.__call__, obj)
【问题讨论】:
-
"我希望
memoization.Memoize成为pass_and_square_time" 这真的是你想要的吗?看起来很简单,但我看不出它有什么意义。
标签: python python-2.7 decorator python-decorators memoization