gpt4 book ai didi

python - 是否可以在python中调用带有变量函数的模块?

转载 作者:行者123 更新时间:2023-11-28 22:51:04 26 4
gpt4 key购买 nike

这里有更多上下文,在 python 中,你如何创建这种效果?

import random
variable = 'randint'
random.[variable](1,3)

请问有什么办法可以写出这种效果的代码吗?除了一堆 {if} block 之外,我没有发现任何东西。

谢谢!

最佳答案

您可以使用内置的 getattr:

>>> import random
>>> variable = 'randint'
>>> getattr(random, variable)(1, 3)
3
>>>

来自docs :

getattr(object, name[, default])

Return the value of the named attribute of object. name must be a string. If the string is the name of one of the object’s attributes, the result is the value of that attribute. For example, getattr(x, 'foobar') is equivalent to x.foobar. If the named attribute does not exist, default is returned if provided, otherwise AttributeError is raised.

关于python - 是否可以在python中调用带有变量函数的模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22074951/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com