There is way, that I discovered, using the locals() binding space and the exec() command. First, you have to create a function object from the exec() builtin and extract it:
def make_function(name, parameter, commands):
func = 'def {name}({parameter}):'.format(name=name, parameter=parameter)
for line in commands:
func += '\n\t' + line
exec(func)
return locals()[name]
>>> func = make_function('help', 'pay', ['pay+=2', 'pay*=5', 'credit = pay//3', 'return credit'])
>>> func(8)
16
Then, you need another function that creates an instance object using the dict attribute. The dict of an object is like it's internal dictionary of attributes that can be accessed via the . commands, it makes a python object similar to a javascript object.
def create_object(names, values):
assert len(names) == len(values)
exec('class one: pass')
obj = locals()['one']()
for i in range(len(names)):
obj.__dict__[names[i]] = values[i]
return obj
>>> func = make_function('help', 'pay', ['pay+=2', 'pay*=5', 'credit = pay//3', 'return credit'])
>>> test_obj = create_object(['help', 'interest', 'message'], [func, 0.5, 'please pay by thursday.'])
>>> test_obj.help(7)
15
>>> test_obj.interest
0.5
>>> test_obj.message
'please pay by thursday.'
This function essentially zips to separate lists together, to create a set of attributes for your instance object.