便捷提取python导入包的属性方法

冬天,洁白的雪花慢慢地飘落下来,落到这里,飘到那里,我们仿佛置身于童话般的雪白世界。在苍茫的大海上,狂风卷集着乌云。在乌云和大海描写大海的散文之间,海燕像黑色的闪电,在高傲的飞翔。

很多时候我们都需要了解下python中导入包的属性方法信息,当然dir 是最便捷的了,不过如果想知道特定的,例如以_ 开头的属性,需要写个筛选,以下是实现筛选的两种方式,主要是练习下yield from 的使用,可以聊作参考~

#法1
def e(start='_', module='os'):
 module = __import__(module)
 def gen_attr():
  for attr in dir(module):
   if attr.startswith(start):
    yield attr
 yield from gen_attr()

#法2 利用生成器推导式更简洁
def e2(start='', module='os'):
 module = __import__(module)
 yield from (attr for attr in dir(module) if attr.startswith(start))


if __name__ == '__main__':
 print (list(e('')))
 print (list(e2('a')))

以上这篇便捷提取python导入包的属性方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

您可能有感兴趣的文章
Python自动化运维-使用Python脚本监控华为AR路由器关键路由变化

Python自动化运维-netmiko模块设备自动发现

Python自动化运维—netmiko模块连接并配置华为交换机

Python自动化运维-利用Python-netmiko模块备份设备配置

Python自动化运维-Paramiko模块和堡垒机实战