【发布时间】:2019-04-02 10:22:38
【问题描述】:
所以我正在研究一个Customer class,它应该是一些其他类的包装器,这些类从服务器和在线检索有关特定客户的信息,如下所示。
class Customer:
def __init__(self, name):
self.name = name
@property
@lru_cache()
def online_info(self):
print('retrieving customer online info')
return Online().search_result(for=self)
@property
@lru_cache()
def server_info(self):
print('retrieving customer server info')
return Server().search_result(for=self)
在线和服务器调用必须是@property 装饰。我面临的问题是尝试缓存 online_info 和 server_info 调用时。缓存必须以某种方式处于类级别,以便即使实例化新闻客户,lru_cache 也会记住来自其他实例化的同名调用的先前调用。注意我的打印声明。这是我想要实现的行为:
>>> cutomer1 = Customer('John')
>>> customer1.online_info
retrieving customer online info
John Smith has the following info bla bla bla ....
>>> cutomer2 = Customer('John')
>>> customer2.online_info # this one will not be calling the function, lru_cache will return the value saved from customer1.online_info
John Smith has the following info bla bla bla ....
有人可以解释我是如何实现这种行为的吗?这可能吗?
【问题讨论】:
-
如果我做
Customer('not John').online_info怎么办?那也应该使用缓存的值吗? -
@Aran-Fey 在这种情况下不会,因为之前从未调用过“no John”
-
您不能在属性上使用
lru_cache,或者至少,即使您的装饰器订单正确(其中和现在一样不正确)。lru_cache的工作原理是查看 函数的参数,而这里你所拥有的只是......什么都没有,因为属性不接受参数。 -
@Aran-Fey 如果您有另一个 Customer('no John').online 信息,在初始的 'no John' 之后,第二个 'no John' 的值将从缓存而不是来自属性调用
-
@MartijnPieters 这不对。有
self参数。如果交换了装饰器,则代码可以正常工作。
标签: python python-3.x class caching properties