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

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

如何在子類中執行和注入策略

如何在子類中執行和注入策略

HUWWW 2021-11-02 16:41:56
有人可以幫助我了解是否有更好的方法在子類中強制執行注入策略(來自常用策略列表)。請在下面找到示例代碼。我并不完全相信將這些策略包裝為靜態方法并在基類中將策略的值提供為 None 。這是因為這里沒有執行策略注入,并且使用繼承解決這個問題看起來并不自然/明顯。我能以更好的方式實現這一目標嗎?def strategy1():    print("strategy1")def strategy2():    print("strategy2")class Base():    strategy = Noneclass Child1(Base):    strategy = staticmethod(strategy1)class Child2(Base):    strategy = staticmethod(strategy2)class Child3(Base):    strategy = staticmethod(strategy1)Child1.strategy()Child2.strategy()Child3.strategy()我的主要要求是跨繼承層次結構的代碼(策略)重用強制子類在覆蓋基類時注入這些策略。
查看完整描述

1 回答

?
汪汪一只貓

TA貢獻1898條經驗 獲得超8個贊

您可以改為使用將策略函數注入的策略類:


import abc


def strategy1(self):

    print("strategy1")


class AbstractClient(metaclass=abc.ABCMeta):

    @abc.abstractmethod

    def execute(self):

        pass


class StrategizedClient(AbstractClient):

    execute = strategy1


class PlanlessClient(AbstractClient):

    pass

這需要 python3,但它會強制您的子類注入一個策略:


>>> StrategizedClient()

<strategy.StrategizedClient object at 0x10fd594a8>

>>> PlanlessClient()

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

TypeError: Can't instantiate abstract class PlanlessClient with abstract methods execute


查看完整回答
反對 回復 2021-11-02
  • 1 回答
  • 0 關注
  • 152 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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