2

Python 2.7

I would like to automotically call a function of a parent object after I instantiate its child

class Mother:

    def __init__(self):
        pass

    def call_me_maybe(self):
        print 'hello son'


class Child(Mother):

    def __init__(self):
        print 'hi mom'


# desired behavior

>>> billy = Child()
hi mom
hello son

Is there a way I can do this?

Edit, from a comment below:

"i should have made it more clearer in my question, what i really want is some sort of 'automatic' calling of the parent method triggered solely by the instantiation of the child, with no explicit calling of the parent method from the child. I was hoping there would be some sort of magic method for this but i dont think there is."

ThriceGood
  • 1,633
  • 3
  • 25
  • 43

3 Answers3

4

You could use super but you should set your superclass to inherit from object:

class Mother(object):
#              ^
    def __init__(self):
        pass

    def call_me_maybe(self):
        print 'hello son'


class Child(Mother):

    def __init__(self):
        print 'hi mom'
        super(Child, self).call_me_maybe()

>>> billy = Child()
hi mom
hello son
Community
  • 1
  • 1
Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139
1

Use super()?

class Child(Mother):
    def __init__(self):
        print 'hi mom'
        super(Child, self).call_me_maybe()
DeepSpace
  • 78,697
  • 11
  • 109
  • 154
  • 4
    Since OP seems to use Python 2 he can't use the convenient `super()`. The 2.x version would be `super(Child, self).call_me_maybe()`. – Hannes Ovrén Jul 22 '16 at 13:15
  • @HannesOvrén: how do you know the OP is using Python 2? – cdarke Jul 22 '16 at 13:18
  • 2
    @cdarke from their `print` statement – Moses Koledoye Jul 22 '16 at 13:19
  • What @cdarke said :) Also, his point about `Mother` inheriting from `object` is important too. – Hannes Ovrén Jul 22 '16 at 13:20
  • @MosesKoledoye: I missed that. I looked through the OP's history and found a python 3 question. – cdarke Jul 22 '16 at 13:22
  • i should have made it more clearer in my question, what i really want is some sort of 'automatic' calling of the parent method triggered solely by the instantiation of the child, with no explicit calling of the parent method from the child. I was hoping there would be some sort of magic method for this but i dont think there is. – ThriceGood Jul 22 '16 at 13:56
1

Since the child class inherits the parents methods, you can simply call the method in the __init__() statement.

class Mother(object):

    def __init__(self):
        pass

    def call_me_maybe(self):
        print('hello son')


class Child(Mother):

    def __init__(self):
        print('hi mom')
        self.call_me_maybe()
Chris Mueller
  • 6,490
  • 5
  • 29
  • 35
  • 1
    Although this does the same thing, OP's request is that you call the parent method. Using `super` helps them know they can call the parent's `__init__` with this technique also. – Moses Koledoye Jul 22 '16 at 13:24