gpt4 book ai didi

python - 运行由字符串定义的类的特定方法

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

我有这个示例代码

class aaa:

@staticmethod
def method(self):
pass

@staticmethod
def method2(self):
pass

command = 'method'

现在我想运行由命令字符串定义的类 aaa 的方法。我怎么能这样做?非常感谢。

最佳答案

不要。很少有理由去处理这种方法引入的问题(安全性、整洁性、性能、可以说是可读性……)。只需使用 command = aaa.method

如果您必须使用字符串(希望有充分的理由),您可以使用getattr,但您应该使用显式的指定所有有效名称的映射(这也使代码在未来不会受到内部重命名/重构的影响):

methods = {
'method': aaa.method,
'method2': aaa.method2,
}
methods[command]()

“这个字符串没有方法”的情况可以这样处理:

method = methods.get(command)
if method is None:
... # handle error/bail out

关于python - 运行由字符串定义的类的特定方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5792798/

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