简体   繁体   English

Python:使用反射从类名调用类成员

[英]Python: Using reflection to invoke class members from the class name

If suppose i have a class name as a string, how can i use reflection to invoke its static member known before-hand? 如果假设我有一个作为字符串的类名,那么如何使用反射来调用其事先已知的静态成员? Some like this: 像这样:

someInspectionMechanism("FooClass").staticMethod()

Use locals() or globals() to get the namespace dictionary, and look for a class with the name you want. 使用locals()globals()获取名称空间字典,然后查找具有所需名称的类。 The fact that you're using a static method is not relevant. 您使用静态方法的事实并不重要。

Example: 例:

class Test:
    @staticmethod
    def method():
        return 'called static method'

assert locals()['Test'].method() == 'called static method'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM