gpt4 book ai didi

ruby - Ruby 在 python 中相当于 cached_property 是什么?

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

基本上,我有一个 Ruby 类,它有一个属性可以进行昂贵的 HTTP 调用以获取一些值,我需要缓存该值,所以下次我访问该属性时,我不必再次调用 HTTP。

http://pydanny.com/cached-property.html

https://wiki.python.org/moin/PythonDecoratorLibrary#Cached_Properties

有 Ruby 版本吗?

最佳答案

假设您的类的实例持续存在,您只需要记住结果。

class Foo
def http_response
@_http_response ||= begin
# your slow I/O bound code here
end
end
end

除非该 block 的结果为假,否则不会再次执行。这个概念有多种变体,例如:

class Foo
def http_response(skip_cache = false)
return @_http_response unless skip_cache || !@_http_response
@_http_response = fetch_http_response
end

private
def fetch_http_response
# your slow I/O bound code here
end
end

关于ruby - Ruby 在 python 中相当于 cached_property 是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26706983/

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