python - 如何从类中的方法动态创建模块级函数

标签 python metaprogramming fabric

我正在尝试从类中的方法动态创建模块级函数。因此,对于类中的每个方法,我想创建一个具有相同名称的函数,该函数创建该类的一个实例,然后调用该方法。

我想这样做的原因是我可以采用面向对象的方法来创建 Fabric 文件。由于 Fabric 将调用模块级函数而不是类的方法,因此这是我的解决方法。

我使用以下链接开始

我想出了下面的代码

import inspect
import sys
import types

class TestClass(object):
    def __init__(self):
        pass

    def method1(self, arg1):
        print 'method 1 %s' % arg1

    def method2(self):
        print 'method 2'

def fabric_class_to_function_magic(module_name):
    # get the module as an object
    print module_name
    module_obj = sys.modules[module_name]
    print dir(module_obj)

    # Iterate over the methods of the class and dynamically create a function
    # for each method that calls the method and add it to the current module
    for method in inspect.getmembers(TestClass, predicate=inspect.ismethod):
        print
        print method
        method_name, method_obj = method

        # create a new template function which calls the method
        def newfunc_template(*args, **kwargs):
            tc = TestClass()
            func = getattr(tc, method_name)
            return func(*args, **kwargs)

        # create the actual function
        print 'code: ', newfunc_template.func_code
        print 'method_name: ', method_name
        newfunc = types.FunctionType(newfunc_template.func_code,
                                     {'TestClass': TestClass,
                                      'getattr': getattr,
                                      'method_name': method_name,
                                      },
                                     name=method_name,
                                     argdefs=newfunc_template.func_defaults,
                                     closure=newfunc_template.func_closure,
                                     )

        # add the new function to the current module
        setattr(module_obj, method_name, newfunc)

# test the dynamically created module level function
thismodule = sys.modules[__name__]
print dir(thismodule)
fabric_class_to_function_magic(__name__)
print dir(thismodule)
method1('arg1')
method2()

我得到以下错误

['TestClass', '__builtins__', '__doc__', '__file__', '__name__', '__package__', 'fabric_class_to_function_magic', 'inspect', 'sys', 'thismodule', 'types']
__main__
['TestClass', '__builtins__', '__doc__', '__file__', '__name__', '__package__', 'fabric_class_to_function_magic', 'inspect', 'sys', 'thismodule', 'types']

('__init__', <unbound method TestClass.__init__>)
code:  <code object newfunc_template at 0x7f8800a28d50, file "test.py", line 85>
method_name:  __init__

('method1', <unbound method TestClass.method1>)
code:  <code object newfunc_template at 0x7f8800a28d50, file "test.py", line 85>
method_name:  method1

('method2', <unbound method TestClass.method2>)
code:  <code object newfunc_template at 0x7f8800a28d50, file "test.py", line 85>
method_name:  method2
['TestClass', '__builtins__', '__doc__', '__file__', '__init__', '__name__', '__package__', 'fabric_class_to_function_magic', 'inspect', 'method1', 'method2', 'sys', 'thismodule', 'types']
Traceback (most recent call last):
  File "test.py", line 111, in <module>
    method1('arg1')
  File "test.py", line 88, in newfunc_template
    return func(*args, **kwargs)
TypeError: method2() takes exactly 1 argument (2 given)

好像是复用函数的引用?有什么想法吗?

更新:这是 Ned Batchelder 修复后的工作代码

def fabric_class_to_function_magic(module_name):
    # get the module as an object
    module_obj = sys.modules[module_name]

    # Iterate over the methods of the class and dynamically create a function
    # for each method that calls the method and add it to the current module
    for method in inspect.getmembers(TestClass, predicate=inspect.ismethod):
        method_name, method_obj = method

        # get the bound method
        tc = TestClass()
        func = getattr(tc, method_name)

        # add the function to the current module
        setattr(module_obj, method_name, func)

更新 2:这是我关于该主题的博文:http://www.saltycrane.com/blog/2010/09/class-based-fabric-scripts-metaprogramming-hack/

最佳答案

您过度思考您的解决方案。将 fabric_class_to_function_magic 的末尾更改为:

    tc = TestClass()
    func = getattr(tc, method_name)

    # add the new function to the current module
    setattr(module_obj, method_name, func)

而且效果很好。不需要创建一个新的函数对象,你的对象上已经有一个由 getattr 返回的对象。 getattr 返回的绑定(bind)方法是可调用的东西。只需将它分配给您的模块属性,您就可以开始了。

关于python - 如何从类中的方法动态创建模块级函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3664302/

相关文章:

python - Django,织物 : What is the best way to manage secret keys to deploy Django projects?

python - 如何检测计算机是否使用 Python 连接到互联网?

python - IntEnum 在 _missing_ 中返回缺失的整数会抛出 TypeError

python - 使用结构进行 django 部署 - TypeError : prepare_deployment() takes exactly 1 argument (0 given)

ruby - 何时使用 `method_missing`

groovy - 使用元类重写 Groovy 中 ArrayList 的方法

python - env.password 在 fab 文件中设置,但进程仍然多次询问 sudo 密码

Python 使用 'consist of' 搜索列表值

python - 如何迭代 python 列表?

python - 在python中动态构建类型