很多時候我們都需要了解下python中導(dǎo)入包的屬性方法信息,當然dir 是最便捷的了,不過如果想知道特定的,例如以_ 開頭的屬性,需要寫個篩選,以下是實現(xiàn)篩選的兩種方式,主要是練習下yield from 的使用,可以聊作參考~
#法1def 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 利用生成器推導(dǎo)式更簡潔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導(dǎo)入包的屬性方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持武林站長站。
新聞熱點
疑難解答