python - 获取函数或类中引用的所有类类型
问题描述
我正在研究代码分析器,并且试图识别 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']
解决方案
一种解决方案可能涉及使用类型注释。设置 to 的返回值和get_bar()
to的返回Bar
值,可以写成如下...get_baz()
Baz
get_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
函数的属性。
推荐阅读
- sql-server - SQL Server 代理不启动
- html - 顶部边框不会出现在导航栏的整个长度上(小屏幕)
- c# - EventStore ClientAPI 订阅问题
- sql - ||是什么意思 '|' || 在甲骨文中?
- java - 防止重新加载 WebView onResume()
- hadoop - 什么是 HDFS 文件夹一分钟内数百个下载请求的最有效解决方案
- javascript - React 函数在第一次调用时不起作用,但每隔一段时间就起作用
- python - Python 类,如何在玩家之间切换
- c - 带有 int[] 数组的 Arduino 上的 FastLED
- selenium - 使用python在数组中分离活动网页的抓取结果