假设我有一个名字列表。我希望能够将这些作为实例函数动态添加到类实例中。我知道 types.MethodType 但从那里到这里我有点新手。基本上我想做的是:
class foo( object ):
def __init__(self):
pass
f = foo()
names = ["a","b","c"]
for name in names:
add name() to f # not sure what to do here
# what I wanted added to instance "f" is this for each name:
def name(self, *args, **kwargs):
print( "My name is %s" % inspect.stack()[0][3] )
print( "__called, args=%r, **kwargs=%r" % (args, kwargs) )
f.a() # ==> calls f.a()
f.b(1,2,3) # calls f.b(1,2,3 )and so on