Python中如何取得類別屬性的列表

高洛峰
發布: 2017-02-11 13:27:01
原創
1492 人瀏覽過

這篇文章主要給大家介紹了在Python中如何獲取類屬性的列表,文中通過示例代碼介紹的很詳細,相信對大家的學習或工作具有一定的參考借鑒價值,有需要的朋友可以參考借鑒,下面來一起看看吧。

前言

最近工作中遇到個需求是要得到一個類別的靜態屬性,也就是說有個類別 Type ,我要動態取得 Type.FTE 這個屬性的值。

最簡單的方案有兩個:

getattr(Type, 'FTE')
Type.__dict__['FTE']
登入後複製

那麼,如果要獲取類屬性的列表,該怎麼做呢?

首先上場的是dir ,它能傳回目前範圍的所有屬性名稱清單:

>>> dir()
['__builtins__', '__doc__', '__name__', '__package__']
>>> dir(list)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
登入後複製

可以配合使用inspect 套件中的功能來過濾:spec

包含:

>>> [i for i in dir(list) if inspect.isbuiltin(getattr(list, i))]
['__new__', '__subclasshook__']
登入後複製

還可以配合callable 來使用:

>>> [i for i in dir(inspect) if inspect.isfunction(getattr(inspect, i))]
['_searchbases', 'classify_class_attrs', 'cleandoc', 'findsource', 'formatargspec', 'formatargvalues', 'getabsfile', 'getargs', 'getargspec', 'getargvalues', 'getblock', 'getcallargs', 'getclasstree', 'getcomments', 'getdoc', 'getfile', 'getframeinfo', 'getinnerframes', 'getlineno', 'getmembers', 'getmodule', 'getmoduleinfo', 'getmodulename', 'getmro', 'getouterframes', 'getsource', 'getsourcefile', 'getsourcelines', 'indentsize', 'isabstract', 'isbuiltin', 'isclass', 'iscode', 'isdatadescriptor', 'isframe', 'isfunction', 'isgenerator', 'isgeneratorfunction', 'isgetsetdescriptor', 'ismemberdescriptor', 'ismethod', 'ismethoddescriptor', 'ismodule', 'isroutine', 'istraceback', 'joinseq', 'namedtuple', 'stack', 'strseq', 'trace', 'walktree']
登入後複製

上面提到了__dict__ ,也可以用它來獲取屬性列表:取得類屬性的列表相關文章請關注PHP中文網!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!