檢視python類的屬性

2021-08-11 00:03:00 字數 1908 閱讀 8301

檢視乙個類的靜態屬性,也就是說有個類 type ,我要動態獲取 type.fte 這個屬性的值。

最簡單的方案有兩個:

getattr(type, 'fte')

type.__dict__['fte']

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

首先上場的是 dir ,它能返回當前範圍的所有屬性名稱列表:

>>> dir()

['__builtins__', '__doc__', '__name__', '__package__']

>>> dir(list)

可以配合使用 inspect 包中的功能來過濾:

>>> [i for i in dir(list) if inspect.isbuiltin(getattr(list, i))]

['__new__', '__subclasshook__']

inspect 包中還包含:

>>> [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']

還可以配合 callable 來使用:

>>> [i for i in dir(inspect) if

not callable(getattr(inspect, i))]

['co_generator', 'co_nested', 'co_newlocals', 'co_nofree', 'co_optimized', 'co_varargs', 'co_varkeywords', 'tpflags_is_abstract', '__author__', '__builtins__', '__date__', '__doc__', '__file__', '__name__', '__package__', '_filesbymodname', 'dis', 'imp', 'linecache', 'modulesbyfile', 'os', 're', 'string', 'sys', 'tokenize', 'types']

上面提到了dict,也可以用它來獲取屬性列表:

>>> list.__dict__.keys()

python類的屬性

一 介紹 1 在python中,如果屬性是以雙下劃線開始的,則該屬性是私有屬性。2 如果在類內部使用私有屬性,則應該在私有屬性前加上 self.二 示例 class book author name page 0 price 0 press a book a.author traceback mos...

python 類的屬性

class person 類屬性,通過類名訪問,屬於整個類,而不是某個物件 nation 中國 限制可以使用的屬性,提高訪問的效率 也可以提高訪問速度,減少記憶體使用 slots name age nation def init self,name self.name name self.natio...

python 類的屬性

類的屬性 屬性的基本使用 屬性的定義和呼叫需要注意以下幾點 屬性存在的意義 訪問屬性時,可以製造出和訪問字段完全相同的假象,由於屬性是由方法變種而來,如果python中沒有屬性,完全可以由方法來替代.屬性的兩種定義方式 python3中全都是新式類,有三種 property裝飾方式 其實就像上面的例...