可能重复:
Python: How to pass arguments to the __code__ of a function?
我有一个代表一个函数的代码对象。当我在代码对象上调用exec时,如何为输入参数p?
指定一个值def x(p):
print p
code_obj = x.__code__
exec code_obj
#TypeError: x() takes exactly 1 argument (0 given)
答案 0 :(得分:1)
恢复重复的答案和评论:
import types
types.FunctionType(code_obj, globals={}, name='x')(1)
要使用方法,可以使用函数类型或未绑定方法,然后将实例作为第一个参数传递,或将函数绑定到实例:
class A(object):
def __init__(self, name):
self.name = name
def f(self, param):
print self.name, param
# just pass an instance as first parameter to a function or to an unbound method
func = types.FunctionType(A.f.__code__, globals={}, name='f')
func(A('a'), 2)
unbound_method = types.MethodType(func, None, A)
unbound_method(A('b'), 3)
# or bound the function to an instance
bound_method = types.MethodType(func, A('c'), A)
bound_method(4)