4

The following piece of Python code uses a superclass solely as the repository of functions that one of more subclasses may draw from:

class Class(object):
    ''' A trivial repository for functions to be inherited '''

    def function(self):
        print self

class Subclass(Class):
    ''' A subclass where the action is'''

    def __init__(self):
        pass

subitem = Subclass()
subitem.function()

This seems to be the minimum amount of coding that fits that purpose.

However, I received a non-argued hint that a better way to code the same would be having a constructor in the superclass and calling it inside the subclass constructor (seemingly a sort of tighter coupling):

class Class(object):
    ''' The function repository, now featuring a constructor'''

    def __init__(self):
        pass

    def function(self):
        print self


class Subclass(Class):
    ''' The same subclass, but its constructor invokes the superclass constructor'''

    def __init__(self):
        Class.__init__(self)

subitem = Subclass()
subitem.function()

The question is... In which way would the second way of subclassing be 'superior' to the first one? Superior might mean more general, applicable to a greater variety of situations and so forth.

Thanks for thinking along.

  • seemingly a sort of tighter binding -- If by that you mean "tighter coupling," classes that inherit from other classes are already tightly coupled. – Robert Harvey May 11 '16 at 14:26
  • @RobertHarvey Remark on word choice taken aboard. – XavierStuvw May 11 '16 at 20:14
12

If you add variables to self in the constructor of Class and don't call Class.__init__() in the constructor of Subclass, then these variables will not be in your Subclass object.

See that question for an example.

In your case, Class is simply a function repository. So, it will not make a difference. However, in the future, you may need to add some variables so the functions in that class will work together. Using self may be convenient for that purpose.

Adding Class.__init__() now may then save you some time if you choose to use self later. Indeed, it may take a long time to figure out that you have forgotten that line in the Subclass constructor.

  • 2
    In other words, functions in the super class are available automatically, but variables in the super class will not be available if it is not constructed explicitly, which is usually done in super().__init__(), but could also be done in subclass. – THN Sep 24 '18 at 21:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.