如何使用类名和方法名调用类的静态方法

3 投票
4 回答
6481 浏览
提问于 2025-04-16 04:55

从一个这样的类开始:

class FooClass(object):
    @staticmethod
    def static_method(x):
        print x

通常,我会用以下方式调用这个类的静态方法:

FooClass.static_method('bar')

有没有可能仅通过类名和方法名来调用这个静态方法呢?

class_name = 'FooClass'
method_name = 'static_method'

4 个回答

2

你可以用 getattr 两次。第一次是在包含这个类的模块上,第二次是在这个类本身上。

class_name = 'Foo'
method_name = 'Bar'

cls = getattr(mod, clsname)
method = getattr(cls, method_name)
method(args)

这样做没有像用装饰器建立一个注册表那么灵活,但如果你不打算这么做,那么这比直接搞复杂的堆栈要好得多,而且在风格上也比直接操作 sys.modules 要干净。

需要注意的是,一个模块可以自我导入,而不会产生不良影响。所以这些类不一定要在不同的模块中才能正常工作。

3

这里有一个粗略的方法:

>>> class FooClass(object):
    @staticmethod
    def static_method(x):
        print x


>>> class_name = 'FooClass'
>>> method_name = 'static_method'
>>> getattr(locals().get(class_name), method_name)("bar")
bar

分步骤讲解:

locals().get(class_name)

首先,找到这个类。在这个例子中,我使用了locals(),因为我知道这个类在本地字典中可以找到。如果这个类不在本地字典里,这一步就会失败。

接下来,找到这个类的方法。

getattr(locals().get(class_name), method_name)

这里用到了getattr()

最后,调用这个方法。

getattr(locals().get(class_name), method_name)("bar")
9

不要像其他回答里说的那样去搞乱locals()。如果你有一个类名是字符串格式,并且需要把它解析出来,最好使用某种注册表。用字典就可以很好地解决这个问题。例如:

class FooClass(object):
    @staticmethod
    def static_method(x):
        print x

registry = {'FooClass':FooClass}

(我假设你会想在这个注册表里添加更多的类)

这样查找就变得非常简单了:

getattr(registry['FooClass'], 'static_method')("bar")

撰写回答