cool77
cool77

Reputation: 1136

super function is returning None along with result

I have below code with parent class Test and subclass MyTest . From outside, i am trying to access the method of the parent class instead of subclass. so i am expecting the display function of the parent class. so, i use super function to achieve this. so far so good. but when i try to assign the return of the super function to a variable say z, i see it prints what i am expecting and also prints 'None'.

class Test(object):
    def display(self, x):
        self.x = x
        print self.x

class MyTest(Test):
    def someother(self):
        print "i am a different method"
    def display(self, x):
        self.x = x
        print "Getting called form MyTest"



a = MyTest()
z = super(type(a), a).display(10)
print z

10
None

I am trying to understand why super function is returning 'None' along with expected value

Upvotes: 1

Views: 2368

Answers (2)

Right leg
Right leg

Reputation: 16730

Your MyTest.display method does not include any return statement. Therefore, return None is implied. As a consequence, z = super(type(a), a).display(10) results in an assignment of None into z.

You need to append a return statement in your method, for example:

def display(self, x):
    self.x = x
    print "Getting called form MyTest"
    return self.x

Upvotes: 1

Netwave
Netwave

Reputation: 42756

Any callable in python that doesn't explicitly use the return on them will return None by default.

So, to fix that just use return instead of just printing:

class Test(object):
    def display(self, x):
        self.x = x
        return self.x

Upvotes: 1

Related Questions