檢視Python對象的屬性
在Python語言中,有些庫在使用時,在網絡上找到的文檔不全,這就需要檢視相應的Python對象是否包含需要的函數或常量。下面介紹一下,如何檢視Python對象中包含哪些屬性,如成員函數、變量等,其中這裡的Python對象指的是類、子產品、執行個體等包含元素比較多的對象。這裡以OpenCV2的Python包cv2為例,進行說明。
由于OpenCV是采用C/C++語言實作,并沒有把所有函數和變量打包,供Python使用者調用,而且有時網絡上也找不到相應文檔;還有OpenCV還存在兩個版本:OpenCV2和OpenCV3,這兩個版本在所使用的函數和變量上,也有一些差别。
1. dir() 函數
dir([object]) 會傳回object所有有效的屬性清單。示例如下:
$ python
Python 2.7.8 (default, Sep 24 2015, 18:26:19)
[GCC 4.9.2 20150212 (Red Hat 4.9.2-6)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import cv2
>>> mser = cv2.MSER()
>>> dir(mser)
['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'detect', 'empty', 'getAlgorithm', 'getBool', 'getDouble', 'getInt', 'getMat', 'getMatVector', 'getParams', 'getString', 'paramHelp', 'paramType', 'setAlgorithm', 'setBool', 'setDouble', 'setInt', 'setMat', 'setMatVector', 'setString']
2. vars() 函數
vars([object]) 傳回object對象的__dict__屬性,其中object對象可以是子產品,類,執行個體,或任何其他有__dict__屬性的對象。是以,其與直接通路__dict__屬性等價。示例如下(這裡是反例,mser對象中沒有__dict__屬性):
>>> vars(mser)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: vars() argument must have __dict__ attribute
>>> mser.__dict__
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'cv2.MSER' object has no attribute '__dict__'
3. help() 函數
help([object])調用内置幫助系統。輸入
>>> help(mser)
顯示内容,如下所示:
Help on MSER object:
class MSER(FeatureDetector)
| Method resolution order:
| MSER
| FeatureDetector
| Algorithm
| __builtin__.object
|
| Methods defined here:
|
| __repr__(...)
| x.__repr__() <==> repr(x)
|
| detect(...)
| detect(image[, mask]) -> msers
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __new__ = <built-in method __new__ of type object>
| T.__new__(S, ...) -> a new object with type S, a subtype of T
按h鍵,顯示幫助資訊; 按 q 鍵,退出。
4. type() 函數
type(object)傳回對象object的類型。
>>> type(mser)
<type 'cv2.MSER'>
>>> type(mser.detect)
<type 'builtin_function_or_method'>
5. hasattr() 函數
hasattr(object, name)用來判斷name(字元串類型)是否是object對象的屬性,若是傳回True,否則,傳回False
>>> hasattr(mser, 'detect')
True
>>> hasattr(mser, 'compute')
False
6. callable() 函數
callable(object):若object對象是可調用的,則傳回True,否則傳回False。注意,即使傳回True也可能調用失敗,但傳回False調用一定失敗。
>>> callable(mser.detect)
True
參考資料
1. https://stackoverflow.com/questions/2675028/list-attributes-of-an-object
2. https://docs.python.org/2/library/functions.html
============== End