I have a class:
class A(object):
def __init__(self):
self._first=1
def a(self):
pass
I want to dynamically add a method to it, but I want the name to be based on input (in my case, based on coded object attributes, but that's besides the point). So, I'm adding methods using the below:
#Set up some variables
a = "_first"
b = "first"
d = {}
instance = A()
#Here we define a set of symbols within an exec statement
#and put them into the dictionary d
exec "def get_%s(self): return self.%s" % (b, a) in d
#Now, we bind the get method stored in d to our object
setattr(instance, d['get_%s' % (b)].__name__, d['get_%s' % (b)])
This all works fine, with one caveat:
#This returns an error
>>> print(instance.get_first())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: get_first() takes exactly 1 argument (0 given)
#This works perfectly fine
>>> print(instance.get_first(instance))
1
Why isn't my instance passing itself to it's new function?