arbyter
arbyter

Reputation: 549

How to extend inherited method by using original in python

I'm trying to extend the functionality of a class method in python, but i don't know exactly how. Here are an example of (obvious wrong) python code witch maybe explains what i want to do:

class A(object):
    def foo(self):
        return dict({'field1':'value1'})

class B(A):
    def foo(self):
        return A.foo().update({'field2':'value2'})

The extension of foo in B should return both fields, A and B.

Upvotes: 1

Views: 134

Answers (1)

unutbu
unutbu

Reputation: 879511

The dict.update method updates the dict but returns None. So you need to be careful to return the dict, not the value (None) returned by update.

In this case, you can "extend" the foo method using super(B, self).foo() or A.foo(self):

class B(A):
    def foo(self):
        dct = super(B, self).foo()
        dct.update({'field2':'value2'})
        return dct

The purpose of super is to resolve inheritance diamonds (which arise due to multiple inheritance). Using super leaves open the possibility that your B can be incorporated into a class structure that uses multiple inheritance. There are pitfalls to using super however. If you wish for your class to support single inheritance only, then

dct = super(B, self).foo()

can be replaced by

dct = A.foo(self)

There are many reasons why one might wish to avoid using multiple inheritance (1, 2, 3, 4). If those reasons apply to your situation, there is nothing wrong with -- and in fact strong reasons for -- using the simpler, more direct

dct = A.foo(self)

instead of super.

Upvotes: 4

Related Questions