2

In Python 3.x with the given class hierarchy, where SubClassZero and SubClassOne inherit from SuperClass;

class SuperClass(object):
    def __init__(self, *args, **kwargs):
        self.thing_zero = "Inherited string."

class SubClassZero(SuperClass):
    def __init__(self, *args, **kwargs):
        SuperClass.__init__(self, *args, **kwargs)
        self.thing_one = "SubClassZero's string."

class SubClassOne(SuperClass):
    def __init__(self, *args, **kwargs):
        SuperClass.__init__(self, *args, **kwargs)
        self.thing_one = "SubClassOne's string."

scz = SubClassZero()
sco = SubClassOne()

If we want to give the subclasses the ability set a title from a kwarg then the __init__ function of SuperClass can be redefined using the the built setattr function like so;

def __init__(self, *args, **kwargs):
    self.thing_zero = "Inherited string."
    if 'title' in kwargs:
        self.title = kwargs['title']
    else:
        self.title = ""

setattr(SuperClass, '__init__', __init__)

But to do that one has to know the previous structure of __init__ to maintain full functionality. Is there a way to somehow add to the __init__ function of SuperClass without completely overwriting it?

James Draper
  • 5,110
  • 5
  • 40
  • 59
  • 1
    Why are you trying to change `SuperClass.__init__`? Why aren't the subclass constructors handling this? – user2357112 Aug 15 '17 at 18:11
  • That's a good point. I'm trying force all of the subclasses of a popular module to inherit the same behavior without having to essentially rewrite the init for superclass. – James Draper Aug 15 '17 at 18:25
  • Then put another class between `SuperClass` and the derived classes, with the behavior you want. – Arya McCarthy Aug 15 '17 at 20:31
  • Thank you @AryaMcCarthy. Yes that would work, but I would like avoid altering the subclasses. I'm trying to alter all of the subclasses of superclass for a python module without having to change the source code. – James Draper Aug 15 '17 at 21:08

0 Answers0