• 技术文章 >常见问题 >Python常见问题

    python如何查看对象的属性

    silencementsilencement2020-03-15 21:46:08原创2914

    在Python语言中,有些库在使用时,在网络上找到的文档不全,这就需要查看相应的Python对象是否包含需要的函数或常量。下面介绍

    一下,如何查看Python对象中包含哪些属性,如成员函数、变量等,其中这里的Python对象指的是类、模块、实例等包含元素比较多的

    对象。这里以OpenCV2的Python包cv2为例,进行说明。

    1. dir() 函数

    dir([object]) 会返回object所有有效的属性列表。示例如下:

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    $ 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__属性):

    1

    2

    3

    4

    5

    6

    7

    8

    >>> 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])调用内置帮助系统。输入

    1

    >>> help(mser)

    显示内容,如下所示:

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    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

    更多技术请关注Python视频教程

    专题推荐:对象
    上一篇:python如何输出不回车换行 下一篇:python怎么判断是文件夹还是文件

    相关文章推荐

    • python里的class怎么写• python class是什么• python如何定义class• python class如何使用

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网