2012-05-27 105 views
20

我看到它在Pyramid tutorial for UX design。我無法弄清楚這個裝飾器是什麼。'@reify'做什麼以及應該在什麼時候使用?

示例代碼,我看到它的用法。

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

回答

33

從源代碼文件:

「」」放使用這種方法的結果(非數據) 描述符裝飾器在第一次調用後的實例字典中, 有效地用實例變量替換裝飾器。「」「」

from the fuzzy notepad blog的描述很好。

它的行爲就像@property,只是該函數一次只被稱爲 ;之後,該值被緩存爲常規屬性。這個 可以讓您在不可變的對象上創建惰性屬性。

因此,在您發佈的代碼中,site_menu可以像緩存屬性一樣訪問。

3

根據doc字符串(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.""" 
相關問題