46

I have created a base class:

class Thing():
    def __init__(self, name):
        self.name = name

I want to extend the class and add to the init method so the that SubThing has both a name and a time property. How do I do it?

class SubThing(Thing):
    # something here to extend the init and add a "time" property

    def __repr__(self):
        return '<%s %s>' % (self.name, self.time)

Any help would be awesome.

MFB
  • 17,535
  • 25
  • 70
  • 115

2 Answers2

61

You can just define __init__ in the subclass and call super to call the parents' __init__ methods appropriately:

class SubThing(Thing):
    def __init__(self, *args, **kwargs):
        super(SubThing, self).__init__(*args, **kwargs)
        self.time = datetime.now()

Make sure to have your base class subclass from object though, as super won't work with old-style classes:

class Thing(object):
    ...
Jesse
  • 4,426
  • 1
  • 17
  • 9
  • 21
    Also instead of referencing `SubThing` in `super`, you can do `super(self.__class__, self).__init__(*args, **kwargs)`. This also works with dynamically created classes using `type()`. – miki725 Oct 03 '12 at 04:33
  • 3
    I get this error with either of those solutions: `TypeError: must be type, not classobj` - the error is triggered by my super line. – TheChymera Oct 15 '15 at 16:53
  • 1
    @TheChymera look at what Jesse wrote: "Make sure to have your base class subclass from object though, as super won't work with old-style classes" – Acsisr Dec 30 '15 at 14:44
  • 1
    One note: I had to swap the order of `self.time = ...` and `super(...`. – Charles Clayton May 15 '19 at 23:45
1

You should write another __init__ method in SubThing and then call the constructor of the superclass to initialize its fields.

This Q&A should provide you some more examples.

Community
  • 1
  • 1
mariosangiorgio
  • 5,400
  • 4
  • 31
  • 45