1

I'm trying to declare a method inside class dynamically. For example :

class Foo (object):
    def __init__ (self):
        super(Foo, self).__init__()
        dict_reference = {a:1, b:2, c:3}
        # This will add atributes a,b and c ...
        self.__dict__.update(dict_reference)
        # ... but I want methods instead, like self.a() return 1
        d = {}
        for k in dict_reference.keys():
            exec "def {method_name}(): return {data}".format(method_name=k, data=dict_reference[k]) in d
        del d['__builtins__']
        self.__dict__.update(d)
        # That's the only solution I found so far ...

There is another solution ?

Cheers

MObject
  • 397
  • 3
  • 14
  • No I'm trying to make methods from dictionary and add them at run time inside the class. So may be I did not express myself properly, I search a proper way to build a method from items of a dict. – MObject May 01 '14 at 13:07

1 Answers1

2

Methods are objects, like any other value in Python too:

class Foo(object):
    def __init__(self, a, b, c):
        self.a = lambda: a
        # or
        def b_():
            return b
        self.b = b_
Daniel
  • 42,087
  • 4
  • 55
  • 81