gpt4 book ai didi

python - '@reify' 有什么作用,什么时候应该使用它?

转载 作者:IT老高 更新时间:2023-10-28 22:25:31 45 4
gpt4 key购买 nike

我在 Pyramid tutorial for UX design 中看到了.我无法弄清楚这个装饰器到底是什么。

我看到其用法的示例代码。

def __init__(self, request):
self.request = request
renderer = get_renderer("templates/global_layout.pt")
self.global_template = renderer.implementation().macros['layout']

@reify
def company_name(self):
return COMPANY

@reify
def site_menu(self):
new_menu = SITE_MENU[:]
url = self.request.url
for menu in new_menu:
if menu['title'] == 'Home':
menu['current'] = url.endswith('/')
else:
menu['current'] = url.endswith(menu['href'])
return new_menu

@view_config(renderer="templates/index.pt")
def index_view(self):
return {"page_title": "Home"}

@view_config(renderer="templates/about.pt", name="about.html")
def about_view(self):
return {"page_title": "About"}

最佳答案

来自源代码文档:

""" Put the result of a method which uses this (non-data) descriptor decorator in the instance dict after the first call, effectively replacing the decorator with an instance variable."""

来自from the fuzzy notepad blog 的描述总结得很好。

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.

因此,在您发布的代码中,site_menu 可以像缓存属性一样被访问。

关于python - '@reify' 有什么作用,什么时候应该使用它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10776244/

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