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): pass def getmembers(klass, members=None): # get a list of all class members, ordered by class if members is None: members = [] for k in klass.__bases__: getmembers(k, members) for m in dir(klass): if m not in members: members.append(m) return members print('A=> :', getmembers(A)) print() print('B=> :', getmembers(B)) print() print('IOError=> :', getmembers(IOError))
>>>
==== RESTART: D:/work/csdn/python_Game1/example/builtin-dir-example-2.py ====
A=> : ['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__dict__', '__module__', '__weakref__', 'a', 'b']
B=> : ['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__dict__', '__module__', '__weakref__', 'a', 'b', 'c', 'd']
IOError=> : ['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__cause__', '__context__', '__dict__', '__setstate__', '__suppress_context__', '__traceback__', 'args', 'with_traceback', 'characters_written', 'errno', 'filename', 'filename2', 'strerror', 'winerror']
>>>
在這個例子裡,輸出基類A的成員函式,輸出派生類B的成員函式。