Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between `super(...)` and `return super(...)`?

Tags:

python

oop

I'm just now learning about python OOP. In some framework's source code, i came across return super(... and wondered if there was a difference between the two.

class a(object):
    def foo(self):
        print 'a'

class b(object):
    def foo(self):
        print 'b'

class A(a):
    def foo(self):
        super(A, self).foo()

class B(b):
    def foo(self):
        return super(B, self).foo()

>>> aie = A(); bee = B()
>>> aie.foo(); bee.foo()
a
b

Looks the same to me. I know that OOP can get pretty complicated if you let it, but i don't have the wherewithal to come up with a more complex example at this point in my learning. Is there a situation where returning super would differ from calling super?

like image 893
Noob Saibot Avatar asked Sep 06 '13 03:09

Noob Saibot


People also ask

What does super () return?

The super() function is used to give access to methods and properties of a parent or sibling class. The super() function returns an object that represents the parent class.

What is return super in Django?

super() returns a delegate object to a parent class, so you call the method you want directly on it: super().

What is super () __ Init__ in Python?

When you initialize a child class in Python, you can call the super(). __init__() method. This initializes the parent class object into the child class. In addition to this, you can add child-specific information to the child object as well.

How does super () work 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

Yes. Consider the case where rather than just printing, the superclass's foo returned something:

class BaseAdder(object):
    def add(self, a, b):
        return a + b

class NonReturningAdder(BaseAdder):
    def add(self, a, b):
        super(NonReturningAdder, self).add(a, b)

class ReturningAdder(BaseAdder):
    def add(self, a, b):
        return super(ReturningAdder, self).add(a, b)

Given two instances:

>>> a = NonReturningAdder()
>>> b = ReturningAdder()

When we call foo on a, seemingly nothing happens:

>>> a.add(3, 5)

When we call foo on b, however, we get the expected result:

>>> b.add(3, 5)
8

That's because while both NonReturningAdder and ReturningAdder call BaseAdder's foo, NonReturningAdder discards its return value, whereas ReturningAdder passes it on.

like image 101
icktoofay Avatar answered Sep 30 '22 21:09

icktoofay