dkv
dkv

Reputation: 7292

Python - Is it possible to define an instance method inside another instance method?

Is it possible to do something like this? (This syntax doesn't actually work)

class TestClass(object):
    def method(self):
        print 'one'
        def dynamically_defined_method(self):
            print 'two'

c = TestClass()
c.method()
c.dynamically_defined_method() #this doesn't work

If it's possible, is it terrible programming practice? What I'm really trying to do is to have one of two variations of the same method be called (both with identical names and signatures), depending on the state of the instance.

Upvotes: 0

Views: 34

Answers (1)

John Szakmeister
John Szakmeister

Reputation: 47032

Defining the function in the method doesn't automatically make it visible to the instance--it's just a function that is scoped to live within the method.

To expose it, you'd be tempted to do:

self.dynamically_defined_method = dynamically_defined_method

Only that doesn't work:

TypeError: dynamically_defined_method() takes exactly 1 argument (0 given)

You have to mark the function as being a method (which we do by using MethodType). So the full code to make that happen looks like this:

from types import MethodType

class TestClass(object):
    def method(self):
        def dynamically_defined_method(self):
            print "two"
        self.dynamically_defined_method = MethodType(dynamically_defined_method, self)

c = TestClass()
c.method()
c.dynamically_defined_method()

Upvotes: 2

Related Questions