我在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"}发布于 2012-05-28 02:42:34
来自源代码文档:
“将使用此(非数据)描述符修饰符的方法的结果放在第一次调用后的实例字典中,从而有效地将修饰符替换为实例变量。”
来自from the fuzzy notepad blog的描述很好地总结了这一点。
它的行为类似于@property,不同之处在于该函数只调用一次;之后,值被缓存为常规属性。这为您提供了在对象上创建惰性属性的方法,这些对象应该是不可变的。
因此,在您发布的代码中,可以像访问缓存属性一样访问site_menu。
发布于 2012-05-28 02:40:34
根据单据字符串(source):
""" 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."""https://stackoverflow.com/questions/10776244
复制相似问题