I am trying to understand how to create objects, that have methods, which are defined by a list of strings. I do not know, how it is called that I am trying to do, so searching is pretty difficult for me at the moment. I was looking into closures a bit, and had a look at decorators and descriptors and now I am very confused.
I was able to boil down my problem into ~20 lines of code below. So I am defining this Dyn
class, which will end up having methods according to the names, given in the __init__
call. It works, but for some reason the methods turn out to be all doing the same
import types
class Dyn(object):
def __init__(self, things=['foo', 'bar', 'baz']):
for t in things:
def method(self, number):
print number*t
setattr(self, t, types.MethodType(method, self))
When I try this, e.g. like so:
first = Dyn()
first.foo(3)
first.bar(1)
the result is:
bazbazbaz
baz
and not:
foofoofoo
bar
as I expected.
Can anyone give me a push into the right direction?