0

I have a Base class with all the common methods. How can I select only the selected methods from this base class and build a child class?

I am not sure how can I make only the required methods available in the child class.

Sample code to explain what I am trying to do

Class Baseclass(object):

    def __init__(self):
        pass

    def method_1(self):
       pass

    def method_2(self):
       pass


Class Child(Baseclass):

    def __init__(self):
        pass

Here in the Child class, If I need only method_1, how can I block the method_2 call?

martineau
  • 119,623
  • 25
  • 170
  • 301
Sijeesh
  • 197
  • 2
  • 9

1 Answers1

3

Blocking access to Baseclass method(s) in its child classes is against Liskov Substitution Principle which is one of main reasons why inheritance exists - substitution of base type by its subtypes with same interface.

If you just want your Child classes to have different subsets of Baseclass methods right approach would be to break Baseclass into mixins (classes) implementing those common methods (it doesn't have to be one mixin per method - you can group them logically by responsibilities) and then use multiple inheritance to create classes with desired sets of features:

class BaseAddMixin:
  def add(self, a, b):
    return a + b

class BaseSubMixin:
  def sub(self, a, b):
    return a - b 

class BaseMulMixin:
  def mul(self, a, b):
    return a * b

# Now we want child class that has add() and mul() but not sub() method
class AddMulChild(BaseAddMixin, BaseMulMixin):
  def do_something(self, a, b):
    return self.mul(a, b) + self.add(a, b)

# We can also have child class that has add() and sub() only
class AddSubChild(BaseAddMixin, BaseSubMixin):
  def do_something(self, a, b):
    return self.add(a, b) * self.sub(a, b)
blami
  • 6,588
  • 2
  • 23
  • 31
  • Multiple inheritance is __not__ "composition" - composition (or more exactly "composition/delegation") is when an object `a` has an object `b` as attribute ("composition") and delegates parts of it's operations to this object ("delegation"). – bruno desthuilliers Feb 12 '19 at 14:47
  • Thanks for this valuable comment, I was used to wrong terminology. I corrected my answer. – blami Feb 12 '19 at 15:36