我有一个奇怪的 idea ,抓取一个列表项并将其称为模块函数,下面是我试图做的:

如果在random module上使用dir(),它将返回其属性的列表,我想获取一个特定项,在本例中是randint,然后使用a,b作为参数将其作为工作函数调用,并变成以下形式randint(a, b)

from random import randint  #to avoid the dot notation and make it simple
a = 10
b = 100
var = dir(random)
print(var)
# here is the result

enter image description here

 #randint index is 55
 print(var[55])
 >>> randint

我无法找到函数randint()的类型,因此可以将列表项转换为它,然后try 以下操作:

something(var[55] + "(a, b)")

有什么方法可以实现我想要做的吗?

推荐答案

您可以使用exec命令来执行任何字符串.

更新了你的代码,下面的答案应该可以

import random
from random import randint  #to avoid the dot notation and make it simple


a = 10
b = 100
var = dir(random)
print(var)

function_string = "random_number= " + var[52] + f"({a},{b})"

print(function_string)
exec(function_string)
print(random_number)

Python-3.x相关问答推荐

如何在Django中创建两个不同权限的用户?

使用Python装载. iso文件

如何在matplotlib中显示次要刻度标签

将字符串转换为python日期时间时出错

Pandas 插入的速度太慢了.对于跟踪代码,什么是更快的替代方案?

如何将python点击参数设置为与选项回调不同的参数的别名?

Python GUI:tkinter应用程序作为Windows的实时桌面

我们可以在每个可以使用 Pandas Join 的用例中使用 Pandas merge 吗?

如何根据索引子列表对元素列表进行分组或批处理?

如何将搜索结果中的所有值保存在另一个列表中?

Python Regex 查找给定字符串是否遵循交替元音、辅音或辅音、元音的连续模式

过滤查询集和Q运算符的不同值

pythondecorator中的变量范围

Python 3.9.8 使用 Black 并导入 `typed_ast.ast3` 失败

sys.stdin.readline() 和 input():读取输入行时哪个更快,为什么?

Pandas 的 EMA 与股票的 EMA 不匹配?

在不关心项目的情况下运行生成器功能的更简单方法

使用 Tensorflow 2.0 在 MNIST 上实现自定义神经网络?

是否在未完成初始化的对象上调用了 del?

谁能给我一个 Python 3 中标准输入和标准输出的快速教程?