【问题标题】:What does '@reify' do and when should it be used?'@reify' 有什么作用,什么时候应该使用它?
【发布时间】:2012-06-02 07:47:32
【问题描述】:

我在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"}

【问题讨论】:

    标签: python pyramid


    【解决方案1】:

    根据文档字符串(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."""
    

    【讨论】:

      【解决方案2】:

      来自源代码文档:

      """ 将使用 this 的方法的结果(非数据) 第一次调用后实例字典中的描述符装饰器, 用实例变量有效地替换装饰器。"""

      from the fuzzy notepad blog 的描述很好地总结了它。

      它的作用类似于@property,只是该函数只被调用过 一次;之后,该值被缓存为常规属性。这 为您提供对本应成为的对象的惰性属性创建 不可变。

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

      【讨论】:

        猜你喜欢
        • 2014-09-29
        • 2011-02-21
        • 1970-01-01
        • 2015-04-10
        • 2012-06-18
        • 2023-04-02
        • 2011-04-15
        • 2017-04-10
        • 2012-03-19
        相关资源
        最近更新 更多