首页 > 解决方案 > 获取函数或类中引用的所有类类型

问题描述

我正在研究代码分析器,并且试图识别 Python 中的函数或类中引用的所有类类型。

例如说我有这个类:

import collections

Bar = collections.namedtuple('Bar', ['bar'])
Baz = collections.namedtuple('Baz', ['baz'])

class Foo(object):
    def get_bar(self):
        return Bar(1)
    def get_baz(self):
        return Baz(2)

我正在寻找一种可以获得函数和类类型的方法。像这样的东西:

print(get_types(Foo.get_bar)) # ['Bar']
print(get_types(Foo.get_baz)) # ['Baz']
print(get_types(Foo)) # ['Bar','Baz']

标签: pythonpython-3.xintrospection

解决方案


一种解决方案可能涉及使用类型注释。设置 to 的返回值和get_bar()to的返回Bar值,可以写成如下...get_baz()Bazget_types()

import inspect
import collections

Bar = collections.namedtuple('Bar', ['bar'])
Baz = collections.namedtuple('Baz', ['baz'])


class Foo(object):
    def get_bar(self) -> Bar:
        return Bar(1)
    def get_baz(self) -> Baz:
        return Baz(2)


def get_types(obj):
    if inspect.isclass(obj):
        methods = [method for method in dir(obj)
                   if callable(getattr(obj, method)) and not method.startswith('_')]
        return [get_types(getattr(obj, method)) for method in methods]

    if callable(obj):
        return [obj.__annotations__['return'].__name__]


def main():
    print(get_types(Foo.get_bar)) # ['Bar']
    print(get_types(Foo.get_baz)) # ['Baz']
    print(get_types(Foo)) # ['Bar','Baz']


if __name__ == '__main__':
    main()

get_types(obj)中,如果obj包含一个类的实例,您可以选择该类的非私有方法并返回get_types()其中的每一个。如果obj包含一个函数,那么我们只返回该return函数的属性。


推荐阅读