在Python語言中,有些庫在使用時,在網絡上找到的文檔不全,這就須要查看相應的Python對象是否包含須要的函數或常量。下面介紹一下,如何查看Python對象中包含哪些屬性,如成員函數、變量等,其中這裏的Python對象指的是類、模塊、實例等包含元素比較多的對象。這裏以OpenCV2的Python包cv2爲例,進行說明。
因爲OpenCV是採用C/C++語言實現,並無把全部函數和變量打包,供Python用戶調用,並且有時網絡上也找不到相應文檔;還有OpenCV還存在兩個版本:OpenCV2和OpenCV3,這兩個版本在所使用的函數和變量上,也有一些差異。html
dir([object]) 會返回object全部有效的屬性列表。示例以下:python
$ 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']
vars([object]) 返回object對象的__dict__屬性,其中object對象能夠是模塊,類,實例,或任何其餘有__dict__屬性的對象。因此,其與直接訪問__dict__屬性等價。示例以下(這裏是反例,mser對象中沒有__dict__屬性):linux
>>> 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__'
help([object])調用內置幫助系統。輸入網絡
>>> help(mser)
顯示內容,以下所示: ssh
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 鍵,退出。函數
type(object)返回對象object的類型。ui
>>> type(mser) <type 'cv2.MSER'>
>>> type(mser.detect) <type 'builtin_function_or_method'>
hasattr(object, name)用來判斷name(字符串類型)是不是object對象的屬性,如果返回True,不然,返回Falsespa
>>> hasattr(mser, 'detect') True >>> hasattr(mser, 'compute') False
callable(object):若object對象是可調用的,則返回True,不然返回False。注意,即便返回True也可能調用失敗,但返回False調用必定失敗。code
>>> callable(mser.detect) True
1. https://stackoverflow.com/questions/2675028/list-attributes-of-an-objectorm
2. https://docs.python.org/2/library/functions.html