簡體   English   中英

如何有條件地選擇實例化調用哪個覆蓋方法?

[英]How to conditionally choose on instantiation which overriding method to call?

我有一系列相互繼承的類。 定義方法但未實現的Base類。 該類是由另一個實現該方法的子類( SubWithRun )。 我想要做的,並通過SubWithSpecificRun類進行了SubWithSpecificRun ,是覆蓋_run方法。

很簡單,但是如何有條件地決定在實例化SubWithSpecificRun時調用哪個_run方法? 默認情況下,它將運行最具體的一個。 給定一些條件,我想運行SubWithSpecificRun.run()或繼承樹上的下一個級別,即SubWithRun.run()

class Base():
    def _run(self):
        raise NotImplementedError
    def run(self):
        self._run()

class SubWithRun(Base):
    def _run(self):
        print('Implementing run method')

class SubWithSpecificRun(SubWithRun):
    def _run(self):
        print('Implementing specific run method')

本質上,我所追求的是這樣的:

SubWithSpecificRun().run() == 'Implementing specific run method'
SubWithSpecificRun(use_specific=False).run() == 'Implementing run method'

您將提供一個run使用或者self._runsuper()._run

class SubWithSpecificRun(SubWithRun):
    def __init__(self, use_specific=True, **kwargs):
        super().__init__(**kwargs)
        self.use_specific = use_specific
    def run(self):
        if self.use_specific:
            return self._run()
        else:
            return super()._run()
    def _run(self):
        print('Implementing specific run method')

SubWithSpecificRun().run() # 'Implementing specific run method'
SubWithSpecificRun(use_specific=False).run() # 'Implementing run method'

這是一種不尋常的模式,可能比您實際需要的解決方案更復雜。 如果您有一些工廠函數根據傳入的值返回SubWithRunSubWithSpecificRun實例,那可能會更好。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM