第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機(jī)立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Python備忘錄/延遲查找屬性裝飾器

Python備忘錄/延遲查找屬性裝飾器

ibeautiful 2019-12-10 13:08:49
最近,我瀏覽了現(xiàn)有的代碼庫,其中包含許多類,其中實例屬性反映了存儲在數(shù)據(jù)庫中的值。我已經(jīng)重構(gòu)了許多這些屬性,以便推遲它們的數(shù)據(jù)庫查找。不會在構(gòu)造函數(shù)中初始化,而只能在初讀時進(jìn)行初始化。這些屬性不會在實例的整個生命周期內(nèi)發(fā)生變化,但是它們是第一次計算的真正瓶頸,只有在特殊情況下才真正訪問。因此,它們也可以在從數(shù)據(jù)庫中檢索出來之后進(jìn)行緩存(因此,它適合于記憶的定義,其中輸入只是“無輸入”)。我發(fā)現(xiàn)自己一遍又一遍地為各種類的各種屬性鍵入以下代碼片段:class testA(object):  def __init__(self):    self._a = None    self._b = None  @property  def a(self):    if self._a is None:      # Calculate the attribute now      self._a = 7    return self._a  @property  def b(self):    #etc我已經(jīng)不知道有沒有使用Python的現(xiàn)有裝飾器來執(zhí)行此操作?或者,是否有合理簡單的方法來定義裝飾器,從而做到這一點(diǎn)?我正在Python 2.5下工作,但是2.6答案如果有很大不同,可能仍然很有趣。注意在Python包含許多現(xiàn)成的裝飾器之前,就曾問過這個問題。我更新它只是為了更正術(shù)語。
查看完整描述

3 回答

?
慕少森

TA貢獻(xiàn)2019條經(jīng)驗 獲得超9個贊

對于各種強(qiáng)大的工具,我都使用bolton。


作為該庫的一部分,您具有cached屬性:


from boltons.cacheutils import cachedproperty


class Foo(object):

    def __init__(self):

        self.value = 4


    @cachedproperty

    def cached_prop(self):

        self.value += 1

        return self.value



f = Foo()

print(f.value)  # initial value

print(f.cached_prop)  # cached property is calculated

f.value = 1

print(f.cached_prop)  # same value for the cached property - it isn't calculated again

print(f.value)  # the backing value is different (it's essentially unrelated value)



查看完整回答
反對 回復(fù) 2019-12-11
?
aluckdog

TA貢獻(xiàn)1847條經(jīng)驗 獲得超7個贊

這是惰性屬性裝飾器的示例實現(xiàn):


import functools


def lazyprop(fn):

    attr_name = '_lazy_' + fn.__name__


    @property

    @functools.wraps(fn)

    def _lazyprop(self):

        if not hasattr(self, attr_name):

            setattr(self, attr_name, fn(self))

        return getattr(self, attr_name)


    return _lazyprop



class Test(object):


    @lazyprop

    def a(self):

        print 'generating "a"'

        return range(5)

互動環(huán)節(jié):


>>> t = Test()

>>> t.__dict__

{}

>>> t.a

generating "a"

[0, 1, 2, 3, 4]

>>> t.__dict__

{'_lazy_a': [0, 1, 2, 3, 4]}

>>> t.a

[0, 1, 2, 3, 4]



查看完整回答
反對 回復(fù) 2019-12-11
?
侃侃無極

TA貢獻(xiàn)2051條經(jīng)驗 獲得超10個贊

我為自己編寫了此代碼...用于真正的一次性計算的惰性屬性。我喜歡它,因為它避免在對象上粘貼額外的屬性,并且一旦激活就不會浪費(fèi)時間檢查屬性是否存在,等等:


import functools


class lazy_property(object):

    '''

    meant to be used for lazy evaluation of an object attribute.

    property should represent non-mutable data, as it replaces itself.

    '''


    def __init__(self, fget):

        self.fget = fget


        # copy the getter function's docstring and other attributes

        functools.update_wrapper(self, fget)


    def __get__(self, obj, cls):

        if obj is None:

            return self


        value = self.fget(obj)

        setattr(obj, self.fget.__name__, value)

        return value



class Test(object):


    @lazy_property

    def results(self):

        calcs = 1  # Do a lot of calculation here

        return calcs

注意:lazy_property該類是一個非數(shù)據(jù)描述符,這意味著它是只讀的。添加__set__方法會阻止其正常工作。



查看完整回答
反對 回復(fù) 2019-12-11
  • 3 回答
  • 0 關(guān)注
  • 390 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號