4

What is the best way to create a parent class that is able to define a set of methods that will be implemented by the base classes?

The problem comes when a class A requires 2 parameters for method_X, while class B requires 3 parameters for the same method.

How can I solve this issue?

class SuperClass:
 def method_X(self):
 ...
class A(SuperClass):
 def method_X(self, a, b):
 ...
class B(SuperClass):
 def method_X(self, a, b, c):
 ...
lmiguelvargasf
71.3k55 gold badges231 silver badges241 bronze badges
asked Sep 20, 2017 at 16:01
12
  • 1
    you can use default arguments to tackle this. Commented Sep 20, 2017 at 16:03
  • 7
    In short: don't. Your subclasses are breaking the contract set by the superclass. Commented Sep 20, 2017 at 16:03
  • 1
    This is one of the gripes in the infamous article super harmful. Commented Sep 20, 2017 at 16:08
  • 1
    @lmiguelvargasf: it still makes it impossible to use subclasses where the contract expected the superclass. You don't know what the method needs. Commented Sep 20, 2017 at 16:24
  • 1
    I no longer read the super-harmful article as a criticism of super, but as a complement to Hettinger's super-super that emphasizes that you need to keep the signature of a super-using method consistent across classes. Commented Sep 20, 2017 at 16:35

1 Answer 1

3

What you're trying to accomplish is a clear violation of Liskov Substitution Principle. Moreover, defining inconsistent interfaces for the same named methods is going to be messy and would severely limit duck typing. Still, if you want to go with it, I think using kwargs instead of named parameters would serve the purpose.

class SuperClass:
 def method_x(self, **kwargs):
 ...
class A(SuperClass):
 def method_x(self, **kwargs):
 if 'a' in kwargs:
 # Do something
answered Sep 20, 2017 at 16:12
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.