2012-05-27 35 views
20

Tôi đã thấy nó trong số Pyramid tutorial for UX design. Tôi không thể tạo ra nhiều thứ trang trí này.'@reify' sẽ làm gì và khi nào nó nên được sử dụng?

Mã mẫu nơi tôi thấy việc sử dụng của nó.

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

Trả lời

33

Từ các tài liệu mã nguồn:

""" Đặt kết quả của một phương pháp trong đó sử dụng này (phi dữ liệu) trình mô tả bộ mô tả trong ví dụ sau cuộc gọi đầu tiên, thay thế hiệu quả trang trí bằng biến mẫu. "" "

Mô tả từ from the fuzzy notepad blog tổng hợp nó một cách độc đáo.

Hoạt động như @property, ngoại trừ chức năng này chỉ được gọi là một lần; sau đó, giá trị được lưu trữ dưới dạng thuộc tính thông thường. Điều này cho phép bạn tạo thuộc tính lười biếng trên các đối tượng có nghĩa là không thay đổi.

Vì vậy, trong mã bạn đã đăng, site_menu có thể được truy cập như một thuộc tính được lưu trong bộ nhớ cache.

3

Theo chuỗi 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.""" 
Các vấn đề liên quan