Python override

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 the parent function from a child class in a function that overrides it. I do not know how to do that.

This is a little difficult to explain, comment if you have problems with understanding.

Edit:

Thanks for the answers to everyone, I almost thought it was impossible.

+4
source share
4 answers

The super() function is designed for such cases. However, it only works on "new style" classes, so you will need to change your Parent definition to inherit from object (in any case, you should always use the "new style" classes).

 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" 
+6
source

Either reference the parent explicitly or (in new-style classes) use super() .

 class Child(Parent): ... def Create(self): return 'The ' + Parent.Create(self) 
+7
source

Its as simple as referencing the base class via super :

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

Use the super function to access the parent super(Child,self).create() to call create from the parent.

0
source

All Articles