0

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.

1
  • It's not clear what you want, but no, this is not possible. dynamically_defined_method is just a function local to the body of method, not a method of TestClass. Commented May 9, 2018 at 23:50

1 Answer 1

2

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()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.