Python類屬性的延遲計算

來源:互聯網
上載者:User
所謂類屬性的延遲計算就是將類的屬性定義成一個property,只在訪問的時候才會計算,而且一旦被訪問後,結果將會被緩衝起來,不用每次都計算。

優點

構造一個延遲計算屬性的主要目的是為了提升效能

實現

class LazyProperty(object):    def __init__(self, func):        self.func = func    def __get__(self, instance, owner):        if instance is None:            return self        else:            value = self.func(instance)            setattr(instance, self.func.__name__, value)            return valueimport mathclass Circle(object):    def __init__(self, radius):        self.radius = radius    @LazyProperty    def area(self):        print 'Computing area'        return math.pi * self.radius ** 2    @LazyProperty    def perimeter(self):        print 'Computing perimeter'        return 2 * math.pi * self.radius

說明

定義了一個延遲計算的裝飾器類LazyProperty。Circle是用於測試的類,Circle類有是三個屬性半徑(radius)、面積(area)、周長(perimeter)。面積和周長的屬性被LazyProperty裝飾,下面來試試LazyProperty的魔法:

>>> c = Circle(2)>>> print c.areaComputing area12.5663706144>>> print c.area12.5663706144

在area()中每計算一次就會列印一次“Computing area”,而連續調用兩次c.area後“Computing area”只被列印了一次。這得益於LazyProperty,只要調用一次後,無論後續調用多少次都不會重複計算。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.