首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >“@reify”做什么,什么时候应该使用它?

“@reify”做什么,什么时候应该使用它?
EN

Stack Overflow用户
提问于 2012-05-28 02:25:04
回答 2查看 7.5K关注 0票数 26

我在Pyramid tutorial for UX design上看到了。我不太明白这个装饰器是怎么回事。

我在示例代码中看到了它的用法。

代码语言:javascript
复制
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"}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-05-28 02:42:34

来自源代码文档:

“将使用此(非数据)描述符修饰符的方法的结果放在第一次调用后的实例字典中,从而有效地将修饰符替换为实例变量。”

来自from the fuzzy notepad blog的描述很好地总结了这一点。

它的行为类似于@property,不同之处在于该函数只调用一次;之后,值被缓存为常规属性。这为您提供了在对象上创建惰性属性的方法,这些对象应该是不可变的。

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

票数 40
EN

Stack Overflow用户

发布于 2012-05-28 02:40:34

根据单据字符串(source):

代码语言:javascript
复制
""" 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."""
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10776244

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档