Pol
Pol

Reputation: 25535

Dynamic assignment of methods in python class

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)

Upvotes: 1

Views: 82

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121486

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))

Upvotes: 6

Related Questions