Possible Duplicate:
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)

最佳答案

恢复重复的答案和评论:

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)

关于python - python中的代码对象-传递参数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11135461/

10-12 13:00
查看更多