簡體   English   中英

在Python中帶有額外參數的父方法

[英]Parent method with extra arguments in Python

父類具有一個稱為“反序列化”的屬性,該屬性是靜態的且帶有一個參數的抽象 每個Child類都實現了該方法。 現在我有一個情況,Child類需要多個參數。 當我向Parent類添加options=None ,子類抱怨它們具有不同的簽名(警告)。 我必須向每個班級添加options=None 那是重構。 我想知道是否可以忽略警告並繼續,還是有更好的解決方案? 還是我必須重構?

class Serializable:
    __metaclass__ = ABCMeta

    @staticmethod
    @abstractmethod
    def deserialize(json_obj, options=None):
        pass

class ChildWithNoExtraArguments(Serializable):

   # warning is here...
   @staticmethod        
   def deserialize(json_obj):
        # some implementation

class ChildWithExtraArgumnets(Serializable):

    @staticmethod
    def deserialize(json_obj, options):
        # some implementation, I need options

您還需要用@staticmethod裝飾子類deserialize實現。 您看到的異常是因為python自動將self添加到每個方法調用中。 然后使用@staticmethod裝飾將停止此行為。

另外,您的第二個實現需要將選項定義為關鍵字參數。 關鍵字參數具有默認值,例如: options=None

class Serializable:
    __metaclass__ = ABCMeta

    @staticmethod
    @abstractmethod
    def deserialize(json_obj, options=None):
        pass

class ChildWithNoExtraArguments(Serializable):

   # warning is here...        
    @staticmethod
    def deserialize(json_obj, options=None):
        # some implementation

class ChildWithExtraArgumnets(Serializable):

    @staticmethod
    def deserialize(json_obj, options=None):
        # some implementation, I need options

暫無
暫無

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

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