'@reify' 有什么作用,什么时候应该使用它? [英] What does '@reify' do and when should it be used?
问题描述
我在用户体验设计金字塔教程.我不太明白这个装饰器是关于什么的.
I saw it in the Pyramid tutorial for UX design. I couldn't make out much what this decorator is all about.
我看到其用法的示例代码.
Sample code where I saw its usage.
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."""
来自来自模糊记事本博客的描述很好地总结了它.
A description from from the fuzzy notepad blog sums it up nicely.
它的作用类似于@property,只是该函数只被调用过一次;之后,该值被缓存为常规属性.这为您提供对本应成为的对象的惰性属性创建不可变.
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 可以像缓存属性一样进行访问.
So in the code you posted, site_menu can be accesses like a cached property.
这篇关于'@reify' 有什么作用,什么时候应该使用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!