怎樣在Python中查詢一個類或一個對象有哪些方法(成員函數)?
答:用函數dir()
查詢對象有哪些方法的示例代碼如下:
dict1 = {
'name': 'suwenhao', 'likes': 'reading', 123: 456}
print(dir(dict1))
運行結果如下:
C:\Users\Administrator\AppData\Local\Programs\Python\Python39\python.exe E:/Project/PycharmProjects/P-001/Files/P-001/current/001-00-臨時測試腳本.py
['__class__', '__class_getitem__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__ior__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__or__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__ror__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
查詢類有哪些方法的示例代碼如下:
print(dir(dict))
運行結果如下:
C:\Users\Administrator\AppData\Local\Programs\Python\Python39\python.exe E:/Project/PycharmProjects/P-001/Files/P-001/current/001-00-臨時測試腳本.py
['__class__', '__class_getitem__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__ior__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__or__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__ror__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
可見,兩個示例代碼的運行結果是一樣的。
這說明查詢對象有哪些方法實際上就是查詢對象的類的方法。