I saw it in the Pyramid tutorial for UX design. I couldn't make out much what this decorator is all about.
我在用于UX设计的金字塔教程中看到了它。我无法弄清楚这个装饰器是什么。
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"}
2 个解决方案
#1
35
From the source code documentation:
从源代码文档:
""" 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."""
msgstr“”“在第一次调用后,在实例dict中放置一个使用此(非数据)描述符装饰器的方法的结果,有效地用实例变量替换装饰器。”“
A description from from the fuzzy notepad blog sums it up nicely.
来自模糊记事本博客的描述很好地总结了它。
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.
它的作用类似于@property,只是该函数只被调用一次;之后,该值将缓存为常规属性。这使您可以在对象上创建惰性属性,这些对象应该是不可变的。
So in the code you posted, site_menu can be accesses like a cached property.
因此,在您发布的代码中,site_menu可以像缓存属性一样进行访问。
#2
3
According to the doc string (source):
根据doc字符串(来源):
""" 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."""
#1
35
From the source code documentation:
从源代码文档:
""" 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."""
msgstr“”“在第一次调用后,在实例dict中放置一个使用此(非数据)描述符装饰器的方法的结果,有效地用实例变量替换装饰器。”“
A description from from the fuzzy notepad blog sums it up nicely.
来自模糊记事本博客的描述很好地总结了它。
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.
它的作用类似于@property,只是该函数只被调用一次;之后,该值将缓存为常规属性。这使您可以在对象上创建惰性属性,这些对象应该是不可变的。
So in the code you posted, site_menu can be accesses like a cached property.
因此,在您发布的代码中,site_menu可以像缓存属性一样进行访问。
#2
3
According to the doc string (source):
根据doc字符串(来源):
""" 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."""