QGerome
QGerome

Reputation: 391

Inherit a sub method in Python

I would like inherit a 'submethod' of a method in python. Could somebody help me to figure out how to do this please ?

Example of what I want to do :

 class A(object):
    def method(self, val):
        def submethod():
            return "Submethod action"
        if not val:
            return submethod()  
        return "Method action"


a = A()

class B(A):
    def method(self, val):
        #inherit submethod ?        
        def submethod():
            return "Another submethod action"

        return super(B,self).method(val)

b = B()
print "A : "
print a.method(True)
>> Method action
print a.method(False)
>> Submethod action
print "B : "
print b.method(True)
>> Method Action
print b.method(False)
Actual answer : 
>> Submethod Action
**Wanted answer : 
>> Another submethod action**

Kind regards,

Quentin

Upvotes: 3

Views: 1136

Answers (2)

NPE
NPE

Reputation: 500177

You can't "inherit" submethod since it's local to method and doesn't even exist until method is run.

Why not simply make it a top-level method of A and B?

Upvotes: 4

jathanism
jathanism

Reputation: 33716

This is called a closure (a function within a function) and does not quite behave like what you're asking. Because functions are not like classes, they do not have the concept of "instances", and therefore any objects internal to the function are not externally accessible unless they are returned by the function.

NB, In Python methods are essentially functions that are bound to a class.

This would be a better pattern:

class A(object):
    def method(self, val):
        if not val:
            return self.submethod()
        return "Method action"

    def submethod():
        return "Submethod action"

You may access internal state of closures, but it's not the same as attribute-style access you're thinking. It's better to avoid them until you fully understand how Python's namespaces and stuff and junk work.

Upvotes: 2

Related Questions