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?
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.
super() returns a delegate object to a parent class, so you call the method you want directly on it: super().
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.
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.
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.
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