Victor Rodriguez
Victor Rodriguez

Reputation: 571

Advantages of Declaring Subclasses using Base Class Constructor in Python

Are there any advantages of declaring and initializing a subclass using a base class constructor method with parameters:

class BaseClass(object):
  def __init__(self, a, b):
    self.a = a
    self.b = b

class SubClass(BaseClass):
  def __init__(self, a, b, c, d):
    BaseClass.__init__(self, a, b)
    # or super().
    self.c = c
    self.d = d

newSubClassInstance = SubClass("one", "two", "three", "four")

Over not using parameters at all and just initializing as follows:

class BaseClass(object):
  def __init__(self):
    self.a = " "
    self.b = " "

class SubClass(BaseClass):
  def __init__(self):
    self.c = " "
    self.d = " "

newSubClassInstance = SubClass()
newSubClassInstance.a = "one"
newSubClassInstance.b = "two"
newSubClassInstance.c = "three"
newSubClassInstance.d = "four"

Or is it just up to how one intends to write and use this code within a program? I'm asking mostly about expectations though; would one be better over another if asked to create this particular task in Python, for example?

Upvotes: 0

Views: 285

Answers (1)

JohanL
JohanL

Reputation: 6891

You should definitely instantiate and setup you class in the __init__ method. When the class is (created and) initilaized it should, if possible, be ready to be used. That is what one would expect from a class.

For some situations, e.g. when trying to mimic an immutable, the values should never be updated after the __init__() call. There is also a penality in updating after initialization, as an update may need to trigger other changes. Think of a GUI where one of the inputs is the size of a window being drawn. If that is set after the Window first appear, it has to be redrawn.

Also, your second approach is bad in another way; you do not even have the self.a and self.b after the __init__() call, as you never call BaseClass.__init__(). This you should always do when inheriting and overriding __init__().

You should also consider replacing your explicit call to BaseClass with a call to super() (as you have written as a comment) as that will handle multiple inheritance better.

Upvotes: 2

Related Questions