Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 590
user1513192 Avatar asked Dec 06 '22 12:12

user1513192


1 Answers

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"
like image 66
Jeremy Avatar answered Dec 18 '22 17:12

Jeremy