查看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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM