gpt4 book ai didi

python - 我可以在 python 3.x 的函数内部动态切换函数吗?

转载 作者:太空宇宙 更新时间:2023-11-03 12:37:48 24 4
gpt4 key购买 nike

在 Python 3.x 中,是否可以在函数或类中动态选择函数?例如在下面的函数中,可以不依赖条件语句而只输入我想使用的方法吗?

def npMethodChooser(n,m,method):
if method == "mean":
return np.random.rand(n,m).mean(axis=1)
if method == "std":
return np.random.rand(n,m).std(axis=1)

最佳答案

可以使用getattr 函数进行动态属性查找。

def npMethodChooser(n, m, method):
return getattr(np.random.rand(n,m), method)(axis=1)

关于python - 我可以在 python 3.x 的函数内部动态切换函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40382147/

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