Cmastris
Cmastris

Reputation: 67

Explicitly setting inherited, unchanged __init__ vs skipping it in Python

If a parent class and child class require the same __init__, I can think of two main ways to do this...

1. Use super() to explicitly declare __init__

class Parent:
    def __init__(self, attr1, attr2):
        self.attr1 = attr1
        self.attr2 = attr2


class Child(Parent):
    def __init__(self, attr1, attr2):
        super().__init__(attr1, attr2)

    def do_something(self):
        return self.attr1 + self.attr2

2. Just inherit __init__

class Parent:
    def __init__(self, attr1, attr2):
        self.attr1 = attr1
        self.attr2 = attr2


class Child(Parent):

    def do_something(self):
        return self.attr1 + self.attr2

Is there a preferred approach here? Basic inheritance should work (and seems to), but is it better to be explicit in how an instance of an object (inherited or not) is initialised?

The main reason I ask is because I've never really seen an examples of __init__ being skipped, but this might just be because usually the __init__ behaviour needs to be changed or added to.

(I've tried searching/reading through a lot of other questions and couldn't find an answer, so apologies if this is a duplicate.)

Thanks!

Upvotes: 2

Views: 224

Answers (1)

janluke
janluke

Reputation: 1677

If the constructor in Child is identical, there's no reason to override it. So I would certainly go for solution 2, since solution 1 adds nothing but code replication. If you followed approach 1, a change in Parent.__init__ would require to change all subclasses __init__ too.

In both solutions, you forgot to access attributes from self though (it should be self.attr1, not attr1).

Upvotes: 2

Related Questions