我有一堂课:
class A(object):
def __init__(self):
self._first=1
def a(self):
pass
我想动态地添加一个方法,但我希望名称基于输入(在我的情况下,基于编码对象属性,但这不是重点)。因此,我正在使用以下方法添加方法:
#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 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
为什么我的实例没有将自己传递给它的新函数?