Jonathan Guymont
Jonathan Guymont

Reputation: 497

Initialize inherited class outside constructor in Python

I have something like this:

from some_module import SomeClass


class BaseClass:
    ...


class AnotherClass(BaseClass, SomeClass):
    def __init__(self, parameter, **kwargs):
        BaseClass.__init__(**kwargs)
        self.parameter

    def some_abstract_method(self, **kwargs):
        # this is an abstract method declared in BaseClass
        # and the arguments **kwargs must be passed here 
        # to respect the interface
        SomeClass.__init__(self.parameter, **kwargs)
        SomeClass.do_something()
        return self

The reason I am doing this is to respect the interface of BaseClass. I am wondering how bad is it to structure the object AnotherClass like this and if there is a better way to achieve what I am trying to do. The only other way I can think of is to do something like this:

class AnotherClass(BaseClass):
    def __init__(self, parameter, **kwargs):
        super().__init__(**kwargs)
        self.parameter

    def some_abstract_method(self, **kwargs):
        self.model = SomeClass(self.parameter, **kwargs)
        self.model.do_something()
        return self.model

But I don't like it because AnotherClass is essentially the same object has SomeClass. Basically, I wonder what the best practice would be here.

Upvotes: 0

Views: 277

Answers (1)

deets
deets

Reputation: 6395

I always prefer composition over inheritance if I can. The reasons are manifold, but let's try and numerate a few ones:

  • less state on the surrounding object.
  • not violating the single concern paradigm.
  • not risking inadvertent name clashes.
  • easier to test.
  • looser coupling.

So I would roll with your second solution if you can.

Upvotes: 1

Related Questions