我一直在测试这个缓存方法/代码: http://code.activestate.com/recipes/498245-lru-and-lfu-cache-decorators/?c=15348
在某些情况下,我得到此(或类似)错误: “AttributeError:'str'对象没有属性' module '”
以下是代码示例,这些工作正常:
if __name__ == '__main__':
@lru_cacheItem(maxsize=20)
def f(x, y):
return 3*x+y
domain = range(5)
from random import choice
for i in range(1000):
r = f(choice(domain), choice(domain))
print('Hits:{0}'.format(f.hits), 'Misses:{0}'.format(f.misses))
@lfu_cacheItem(maxsize=20)
def f(x, y):
return 3*x+y
domain = range(5)
from random import choice
for i in range(1000):
r = f(choice(domain), choice(domain))
print('Hits:{0}'.format(f.hits), 'Misses:{0}'.format(f.misses))
@lru_cacheItem(maxsize=20)
def myString(a, b):
return '{0} and {1}'.format(a, b)
a = 'crap'
b = 'shit'
for i in range(1000):
r = myString(a, b)
print('Hits:{0}'.format(myString.hits), 'Misses:{0}'.format(myString.misses))
而这不是:
if __name__ == '__main__':
class P4client(object):
def __init__(self):
pass
def checkFileStats(self, filePath):
results = 'The filepath: {0}'.format(filePath)
print results
return results
p4client = P4client()
filePath = (r"C:\depot\tester.tga")
@lfu_cacheItem
def p4checkFileStats(filePath):
'''Will cache the fstats return'''
p4checkResults = p4client.checkFileStats(filePath)
return p4checkResults
p4checkFileStats(filePath)
我不知道如何解决这个问题......它似乎是functools中的一个问题,我假设某种程度上我正在调用我正在包装的函数中的类/方法吗?
答案 0 :(得分:6)
@lfu_cacheItem
def p4checkFileStats(filePath):
这里缺少括号:
@lfu_cacheItem()
def p4checkFileStats(filePath):
所有期望“选项”的装饰者,即你可以用作:
@decorator(a=Something, b=Other, ...)
def the_function(...):
必须在装饰时始终被称为,即使您不提供参数:
@decorator()
def the_function(...):
为什么你想知道?好吧,首先要记住装饰器是接受函数作为参数的普通函数:
In [1]: def hooray(func):
...: print("I'm decorating function: {.__name__}".format(func))
...: return func
In [2]: @hooray
...: def my_function(): pass
I'm decorating function: my_function
正如您所看到的,hooray
被称为。事实上,这是使用装饰器时真正发生的事情:
In [3]: def my_function(): pass
...: my_function = hooray(my_function)
...:
I'm decorating function: my_function
现在,如果要将选项传递给装饰器,可以创建一个返回装饰器的函数。这正是您链接的食谱lfu_cache
所发生的情况:
def lfu_cache(maxsize=100):
# ...
def decorating_function(user_function):
# ...
return decorating_function
现在,您可以看到lfu_cache
确实是一个功能。这个函数创建一个名为decorating_function
的装饰器并返回它。这意味着在致电时:
@lfu_cache(maxsize=20)
def my_function(): pass
这就是:
def my_function(): pass
decorator = lfu_cache(maxsize=20)
my_function = decorator(my_function)
如您所见,首先调用lfu_cache
,并返回装饰器。然后调用装饰器来装饰该功能。
如果忘记括号会怎么样?这是什么:
@lfu_cache
def my_function(): pass
办?
非常简单,它使用lfu_cache
作为简单的装饰器:
def my_function(): pass
my_function = lfu_cache(my_function)
但这很糟糕!您将函数作为maxsize
参数传递,lfu_cache
返回的值是之前的decorating_function
!
了解有关装饰器的更多信息,请阅读this所以回答。