5
我使用的是装饰:如何在Python中使用doctest和装饰函数?
class Memoized(object):
__cache = {}
def __init__(self, func):
self.func = func
key = (func.__module__, func.__name__)
# print key
if key not in self.__cache:
self.__cache[key] = {}
self.mycache = self.__cache[key]
def __call__(self, *args):
try:
return self.mycache[args]
except KeyError:
value = self.func(*args)
self.mycache[args] = value
return value
except TypeError:
return self.func(*args)
def __get__(self, obj, objtype):
return functools.partial(self.__call__, obj)
def reset(self):
for v in self.__cache.itervalues():
v.clear()
和功能:
@Memoized
def is_tile_inside_border(x, y, z, border):
'''Checks if a tile is inside border or not
>>> is_tile_inside_border(85,53,7,'iran')
3
>>> is_tile_inside_border(85,15,7,'iran')
0
'''
binary_data = get_border_binary(border, z)
return isInside((x, y), binary_data)
但使用文档测试模块(蟒蛇mycode.py -v)时:
if __name__ == '__main__':
import doctest
doctest.testmod()
Python可以” t在文档字符串中找到测试。我知道这是装饰者的问题。但我该如何解决它?
PS:functools.update_wrapper(self, func)
不工作!
你试过了'functools.wraps'装饰? http://stackoverflow.com/questions/308999/what-does-functools-wraps-do –
[相关的机票](http://bugs.python.org/issue1108) – shx2
@AndrewGorcester我研究了链接,谢谢。但是我在摆弄装饰类CLASS时如何使用* wraps? – Farsheed