Python使用dir獲取類的方法列表

2021-08-06 02:41:11 字數 1285 閱讀 4303

使用python的內建方法dir,可以範圍乙個模組中定義的名字的列表。官方解釋是:

docstring:

dir([object]) -> list of strings

if called without an argument, return the names in the current scope.

else, return an alphabetized list of names comprising (some of) the attributes

of the given object, and of attributes reachable from it.

if the object supplies a method named __dir__, it will be used; otherwise

the default dir() logic is used and returns:

for a module object: the module's attributes.

for a class object: its attributes, and recursively the attributes

of its bases.

for any other object: its attributes, its class's attributes, and

recursively the attributes of its class's

base

classes.

通過dir方法,我們可以在乙個類的內部,獲取當前類的名字滿足某些特徵的所有方法。下面是乙個例子:

class

a(object):

defa_x_1

(self):

pass

defa_x_2

(self):

pass

defa_x_3

(self):

pass

defget_a_x_methods

(self):

return filter(lambda x: x.startswith('a_x') and callable(getattr(self,x)), dir(self))

執行:

print a().get_a_x_methods()
輸出結果為:

> ['a_x_1', 'a_x_2', 'a_x_3']

python隱藏類的屬性 重寫 dir

python類的繼承和方法重寫總結python 咱們都知道類能夠繼承,經過繼承能夠實現 的復用,使 看起來更加簡潔ide 好比 函式 class b a pass 定義了乙個名為b的類,它繼承於a,咱們把b叫作a的子類,a叫作b的超類 父類 spa 方法重寫物件 當子類定義了乙個和超類相同名字的方法...

python裡使用dir函式檢視乙個類所有成員函式

如果乙個類是別人編寫的,又沒有幫助文件,怎麼樣來檢視所有成員函式呢?就可以使用下面的 file builtin dir example 2.py class a def a self pass def b self pass class b a def c self pass def d self ...

VBA中Dir函式的使用

dir 會返回匹配 pathname 的第乙個檔名。若想得到其它匹配 pathname 的檔名,再一次呼叫dir,且不要使用引數。如果已沒有合乎條件的檔案,則 dir 會返回乙個零長度字串 一旦返回值為零長度字串,並要再次呼叫 dir 時,就必須指定 pathname,否則會產生錯誤。檔案數確定時,...