gpt4 book ai didi

python - @reify 每次调用都执行数据库查询?

转载 作者:行者123 更新时间:2023-12-04 14:56:56 24 4
gpt4 key购买 nike

基于 this comment关于具体化,

It acts like @property, except that the function is only ever called once; after that, the value is cached as a regular attribute. This gives you lazy attribute creation on objects that are meant to be immutable.

我有这个自定义具体化类:

class reify(object):
def __init__(self, wrapped):
self.wrapped = wrapped

def __get__(self, inst):
if inst is None:
return self
val = self.wrapped(inst)
setattr(inst, self.wrapped.__name__, val)
return val

它的用法如下:

@reify
def user_details(self, user_id):
try:
# function that executes db query, returns dict
return user_details_from_id(self._dbconn, user_id)
except Exception as e:
pass

很明显,我们只需执行 name = self.user_details.get("name") 就可以使用它。

这按预期工作,但不确定这是缓存结果还是每次调用时都执行查询,我如何确认?我的意思是这个实现是否正确? (没有数据库控制台)

最佳答案

def user_details(self, user_id) 这样的签名有太多的参数,@reify 甚至 @property 都无法支持。它应该是 def user_details(self)reify 装饰器将修改属性 self.user_details 以在实例持续时间内返回相同的值。请注意,它不是全局的,而是针对每个实例的,因为它使用 self。要确认它正在缓存,您只需将打印语句放在 user_details 函数中,以确认它在每个实例中仅被调用一次。

关于python - @reify 每次调用都执行数据库查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67780893/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com