Skip to content
Advertisement

Overriding in Python

I want to be able to do the following

class Parent:
    def __init__(self):
        pass
    def Create(self):
        return 'Password'

class Child(Parent):
    def __init__(self):
        self.Create()
    def Create(self):
        return 'The '+self.Create #I want to return 'The Password'

I would like to get a parent function from a child class in a function that is overriding it. I am not sure how to do this.

This is a little hard to explain, comment if you are having trouble understanding.

Edit:

Thanks for the answers everyone, I almost thought that this was impossible.

Advertisement

Answer

The super() function is meant for cases like this. However, it only works on “new-style” classes, so you’ll need to modify your definition of Parent to inherit from object as well (you should always be using “new-style” classes, anyway).

class Parent(object):
    def __init__(self):
        pass
    def Create(self):
        return 'Password'

class Child(Parent):
    def __init__(self):
        self.Create()
    def Create(self):
        return 'The ' + super(Child, self).Create()


print Child().Create() # prints "The Password"
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement