Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/291.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 是否可以在模块中动态创建函数/变量?_Python - Fatal编程技术网

Python 是否可以在模块中动态创建函数/变量?

Python 是否可以在模块中动态创建函数/变量?,python,Python,比如说,我有一个通用函数f(输入,种类)和一长串kind。我想为列表中的每个kind创建函数f_kind(input)。与其通过f\u kind1=partial(f,kind=kind1)手动创建它们,还可以通过列表上的循环(类似于类内的setattr(class\u name,method\u name,method))更动态地创建它们吗?我很久以前读过Guido van Rossum的一篇关于用Python实现的文章,这让你想起了你的问题,因为在它的核心,这就是你正在做的事情 需要对它进行

比如说,我有一个通用函数
f(输入,种类)
和一长串
kind
。我想为列表中的每个
kind
创建函数
f_kind(input)
。与其通过
f\u kind1=partial(f,kind=kind1)
手动创建它们,还可以通过列表上的循环(类似于类内的
setattr(class\u name,method\u name,method)
)更动态地创建它们吗?

我很久以前读过Guido van Rossum的一篇关于用Python实现的文章,这让你想起了你的问题,因为在它的核心,这就是你正在做的事情

需要对它进行调整以处理类,但我认为它可能是比使用
setattr()
更好的方法来实现您的目标

mm.py:

''' MultiMethod module. '''

_registry = {}

class MultiMethod(object):
    def __init__(self, name):
        self.name = name
        self.typemap = {}

    def __call__(self, *args):
        types = tuple(arg.__class__ for arg in args)
        function = self.typemap.get(types)
        if function is None:
            raise TypeError("no match")
        return function(*args)

    def register(self, types, function):
        if types in self.typemap:
            raise TypeError("duplicate registration")
        print('registering: {!r} for args: {}'.format(function.__name__, types))
        self.typemap[types] = function

def multimethod(*types):
    def register(function):
        name = function.__name__
        mm = _registry.get(name)
        if mm is None:
            mm = _registry[name] = MultiMethod(name)
        mm.register(types, function)
        return mm

    return register
from mm import multimethod

@multimethod(int)
def f(input):
    print('f_{}({!r}) called'.format(type(input).__name__, input))


@multimethod(str)
def f(input):
    print('f_{}({!r}) called'.format(type(input).__name__, input))

f('answer')
f(42)

@multimethod(float)
def f(input):
    print('f_{}({!r}) called'.format(type(input).__name__, input))

f(3.141529)
示例用法

mm_测试。py:

''' MultiMethod module. '''

_registry = {}

class MultiMethod(object):
    def __init__(self, name):
        self.name = name
        self.typemap = {}

    def __call__(self, *args):
        types = tuple(arg.__class__ for arg in args)
        function = self.typemap.get(types)
        if function is None:
            raise TypeError("no match")
        return function(*args)

    def register(self, types, function):
        if types in self.typemap:
            raise TypeError("duplicate registration")
        print('registering: {!r} for args: {}'.format(function.__name__, types))
        self.typemap[types] = function

def multimethod(*types):
    def register(function):
        name = function.__name__
        mm = _registry.get(name)
        if mm is None:
            mm = _registry[name] = MultiMethod(name)
        mm.register(types, function)
        return mm

    return register
from mm import multimethod

@multimethod(int)
def f(input):
    print('f_{}({!r}) called'.format(type(input).__name__, input))


@multimethod(str)
def f(input):
    print('f_{}({!r}) called'.format(type(input).__name__, input))

f('answer')
f(42)

@multimethod(float)
def f(input):
    print('f_{}({!r}) called'.format(type(input).__name__, input))

f(3.141529)
输出:

为参数(,)注册:“f”
正在为参数注册:“f:(,)
f_str(“应答”)呼叫
f_int(42)调用
正在为参数注册:“f:(,)
f_浮点数(3.141529)调用

是的,但您可能正在仔细构建一些对除您之外的任何人来说都非常困难的东西(将来您自己可能会意外地在一年或更长的时间内回到此代码,并且记不起代码到底为什么如此复杂/不可理解)。当然,你试过在循环中使用partial吗?@juanpa.arrivillaga我的意思是,如何真正做到这一点?我似乎无法访问模块本身内部的
\uuu dict\uuu
之类的内容。您可以使用
globals()?我的意思是动态生成这些东西是个坏主意。