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?
newSubClassshould benewInstancebecause it’s an object of typeSubClassand not a class. Other than that, both versions of the code achieve the same. If you’re familiar with private and protected class members in other programming languages (e.g. C++ or Java) then constructors make more sense, but for Python it doesn’t much matter either way. (Also, please callsuper().__init__()in your second example to ensure complete initialization.)