I have an odd question, and seeing as the real context is fairly complex I've made a simple example. I have two classes Base and Child. Each share a method of the the same name go. What I want the Child class to be able to do is inherit the go method from Base. However, when I call the go method on Child I want it to do some things (In this case multiply the attribute A by 2), then call the go method that it inherited from Base.
In this example calling go on Base would print 35, while I want Child to print 70.
class Base :
def __init__ (self) :
self.A = 35
def go (self) :
print self.A
class Child (Base) :
def __init__ (self) :
Base.__init__(self)
def go (self) :
self.A = self.A * 2
# Somehow call Base's **go** method, which would print 70.
I understand that it's typically not a good idea to do this (seeing as it could be confusing), however in the context of what I'm doing it makes sense.
Python does not support function overloading. When we define multiple functions with the same name, the later one always overrides the prior and thus, in the namespace, there will always be a single entry against each function name.
Inheritance allows us to define a class that inherits all the methods and properties from another class. Parent class is the class being inherited from, also called base class. Child class is the class that inherits from another class, also called derived class.
In general it is necessary. And it's often necessary for it to be the first call in your init. It first calls the init function of the parent class ( dict ).
The super() function in Python makes class inheritance more manageable and extensible. The function returns a temporary object that allows reference to a parent class by the keyword super. The super() function has two major use cases: To avoid the usage of the super (parent) class explicitly.
This is absolutely a fine thing to do. What you're looking for is super()
.
class Child (Base):
def __init__ (self):
super(Child, self).__init__()
def go(self):
self.A = self.A * 2
super(Child, self).go()
In Python 3 you can use it without arguments because it will detect the correct ones automatically.
Edit: super()
is for new-style classes, which you should use anyway. Just declare any class which doesn't inherit from another as inheriting from object
:
class Base(object):
Also, all those extra spaces before and after parenthesis are not considered good python style, see PEP8.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With