python - 使用方法名称字符串检索方法? Python

标签 python

我想知道在 Python 中是否有可能通过使用它的字符串名称在不同的函数中找到一个方法。

在一个函数中,我传入了一个方法:

def register(methods):
    for m in methods:
        messageType = m.__name__
        python_client_socket.send(messageType)


register(Foo)

在接受发送过来的字符串的不同方法中,我希望能够将数字与字典中的方法相关联(即 methodDict = {1: Foo, 2:Bar, etc. ..} )

Python有没有办法从字符串中找到方法?

最佳答案

如果您确定方法名称(请不要将其用于任意输入):

getattr(someobj, methodDict[someval])

关于python - 使用方法名称字符串检索方法? Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3105684/

相关文章:

python - tkinter 动态创建标签和条目

python - Python 3 确保数组参数尺寸正确的方法是什么?

python - 必须使用 LocaleRegexProvider 实例作为第一个参数调用未绑定(bind)方法 __init__() (改为使用 RegexURLPattern 实例)

python - 如何在遗传算法工具箱Deap中生成0到1之间的随机数

python - Tornado 异步 http 客户端 block

python - 什么时候 ndarray 的大小不固定?

python - 如何为时间序列数据帧添加行?

python - 按组查找 Pandas 列的列发生了多少次切换

python - 将 Fasttext 向量转换为单词

python - 如何从 python 脚本将文件从 Windows 系统复制到任何其他远程服务器?