1

I want to create a bunch of methods in class __init__ method dynamically. Havent had luck so far.

CODE:

class Clas(object):
    def __init__(self):
        for i in ['hello', 'world', 'app']:
            def method():
                print i
            setattr(self, i, method)

Than I crate method and call method that is fitst in list.

>> instance = Clas()

>> instance.hello()

'app'

I expect it to print hello not app. WHat is the problem? In addition, each of these dynamically assigned methods referred to the same function in memory, even if I do copy.copy(method)

1 Answer 1

6

You need to bind i properly:

for i in ['hello', 'world', 'app']:
    def method(i=i):
        print i
    setattr(self, i, method)

The i variable then is made local to method. Another option is to use a new scope (separate function) generating your method:

def method_factory(i):
    def method():
        print i
    return method 

for i in ['hello', 'world', 'app']:
    setattr(self, i, method_factory(i))
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.