Amish Shabani
Amish Shabani

Reputation: 759

Parent method with extra arguments in Python

Parent class has a property called 'deserialize' that is static and abstract with one argument. Each Child class implemented that method. Now I have a situation that Child class needs more than one argument. When I add options=None to Parent class, children classes complain that they have a different signature(warning). I have to add options=None to each class. That is a refactoring. I want to know if I can omit the warning and continue, or there is a better solution? Or do I have to refactor?

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

Upvotes: 2

Views: 810

Answers (1)

Matt Hardcastle
Matt Hardcastle

Reputation: 678

You need to decorate your child classes deserialize implementation with @staticmethod too. The exception you're seeing is because python is automatically adding self to each of the method calls. Decorating then with @staticmethod stops this behavior.

Additionally, you're second implementation needs to define options as a keyword argument. Keyword arguments have default values, for instance: 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

Upvotes: 3

Related Questions