Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Methods of the same name and inheritance, Python

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.

like image 400
rectangletangle Avatar asked Aug 09 '11 21:08

rectangletangle


People also ask

Can we have two methods in a class with the same name Python?

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.

Are methods inherited in Python?

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.

Is super () necessary Python?

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 ).

How does super () work in Python?

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.


1 Answers

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.

like image 172
agf Avatar answered Nov 15 '22 01:11

agf