私はクラスを持っています:
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)])
これはすべて正常に機能しますが、1 つの注意点があります。
#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
インスタンスが自分自身を新しい関数に渡さないのはなぜですか?