亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

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

python - 如何在返回時始終強制調用類方法

python - 如何在返回時始終強制調用類方法

守候你守候我 2021-10-10 14:35:17
我有一ReportEntry堂課class ReportEntry(object):  def __init__(self):      # Many attributes defined here  ... # Lot many setattr/getattr here  def validate(self):      # Lot of validation code in here      return self多個其他類保持has-a與ReportEntry類的關系class A(object):  def test1(self):    t1 = ReportEntry()    # Assign the attribute values to t1    return t1.validate()  def test2(self):    t2 = ReportEntry()    # Assign the attribute values to t2    return t2.validate()并且有多個這樣的類,如 A.我需要強制執行的每個ReportEntry類實例調用validate()上return或許只是之前return?;旧?,任何實例ReportEntry都不應逃避驗證,因為如果缺少某些內容,最終報告生成將失敗。我怎樣才能做到這一點?
查看完整描述

3 回答

?
慕婉清6462132

TA貢獻1804條經驗 獲得超2個贊

我可以考慮兩種方法來解決這個問題。在不了解更多實現細節的情況下,我不能說更多:


裝飾你的方法:每個返回實例都通過裝飾器函數運行。您可能希望將其作為獨立函數或類的一部分,具體取決于您的特定用例。


def validate(func):

    return func().validate()


class A(object):

    @validate

    def test1(self):

        t1 = ReportEntry()

        # Assign the attribute values to t1

        return t1

    @validate

    def test2(self):

        t2 = ReportEntry()

        # Assign the attribute values to t2

        return t2

更新 __setattr__ 并裝飾你的類:


def always_validate(cls):

    # save the old set attribute method

    old_setattr = getattr(cls, '__setattr__', None)

    def __setattr__(self, name, value):

        # set the attribute

        validate(name, value)

        old_setattr(self, name, value)


    cls.__setattr__ = __setattr__


    return cls

然后你可以裝飾你的 ReportEntry:


@alway_validate

class ReportEntry(object):

    ...


查看完整回答
反對 回復 2021-10-10
?
繁花如伊

TA貢獻2012條經驗 獲得超12個贊

一種方法,我能想到的是定義__enter__并__exit__在那里方法validate在被稱為__exit__中ReportEntry


class ReportEntry(object):

  def __enter__(self):

    return self

  def __init__(self):

  # Many attributes defined here

  ... # Lot many setattr/getattr here

  def validate(self):

    # Lot of validation code in here

    return self

  def __exit__(self, a,b,c):

    self.validate()

    return True


# And then use it as

with ReportEntry() as report:

    ...

但同樣,這只會在使用時強制執行 with ReportEntry() as report:


查看完整回答
反對 回復 2021-10-10
  • 3 回答
  • 0 關注
  • 243 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號