[Tutor] calling a superclass method after overriding it

Serdar Tumgoren zstumgoren at gmail.com
Tue Sep 22 19:14:34 CEST 2009


> You're actually already doing it:  look at __init__.
>
> __init__ is overridden in your subclass, so you call super(Child,
> self).__init__() to initialise the class using the parent
> (superclass)'s __init__ method.

Yes indeed. Thanks for pointing it out. In case it helps anyone else
out down the road, below is a bit of test code that appears to work
(of course, please let me know if the way I've done the call has some
unexpected (at least by me) side effects):

def result_of_GENERIC_SQLcall():
    name = "This name came from the Parent class"
    return name

def result_of_SPECIALIZED_SQLcall_for_child():
    name = None
    return name

class Parent(object):
    def __init__(self):
        self.add_name()
        print self.name, self.__class__

    def add_name(self):
        self.name = result_of_GENERIC_SQLcall()

class Child(Parent):
    def __init__(self):
        super(Child, self).__init__()

    def add_name(self):
        name = result_of_SPECIALIZED_SQLcall_for_child()
        try:
            name + ''
            self.name = name
        except TypeError:
            #default to the superclass's add_name method
            super(Child, self).add_name()

Meantime, many thanks!!


More information about the Tutor mailing list