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

2 投票
3 回答
4482 浏览
提问于 2025-04-16 16:27

我有一段示例代码

class aaa:

    @staticmethod
    def method(self):
        pass

    @staticmethod
    def method2(self):
        pass

command = 'method'

现在我想通过一个命令字符串来运行类aaa中的某个方法。我该怎么做呢?非常感谢。

3 个回答

1

你可以使用 getattr 来通过名字获取一个对象的属性。

In [141]: class Foo(object):
   .....:     def frob(self):
   .....:         print "Frobbed"
   .....:         
   .....:         

In [142]: f = Foo()

In [143]: getattr(f, 'frob')
Out[143]: <bound method Foo.frob of <__main__.Foo object at 0x2374350>>

In [144]: _()
Frobbed
3

首先,删除你在 staticmethod 中的 self 参数——因为 staticmethod 的主要特点就是它们不需要 self 参数。然后,使用

method = getattr(aaa, command)
method()

或者简单地使用

getattr(aaa, command)()

来调用名为 command 的方法。

(我只是好奇你为什么一开始不直接用 command = aaa.method,不过肯定有些情况下这样做是不可能的。)

4

别这样做。很少有理由去处理这种方法带来的问题(比如安全性、代码整洁性、性能,还有可读性等等)。直接使用 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

撰写回答