[英]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.