How Do I Perform Introspection on an Object in Python 2.x?

前端 未结 5 1443
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-05 23:42

I\'m using Python 2.x and I have an object I\'m summoning from the aether; the documentation on it is not particularly clear. I would like to be able to get a list of prope

5条回答
  •  长情又很酷
    2020-12-06 00:22

    How about something like:

    >>> o=object()
    >>> [(a,type(o.__getattribute__(a))) for a in dir(o)]
    [('__class__', ), ('__delattr__', ), 
    ('__doc__', ), ('__format__', ),
    ('__getattribute__', ), ('__hash__', ),
    ('__init__', ), 
    ('__new__', ),
    ('__reduce__', ),
    ('__reduce_ex__', ),
    ('__repr__', ), ('__setattr__', ),
    ('__sizeof__', ),
    ('__str__', ),
    ('__subclasshook__', )]
    >>> 
    

    A more structured method will be to use the inspect module:

    The inspect module provides several useful functions to help get information about live objects such as modules, classes, methods, functions, tracebacks, frame objects, and code objects. For example, it can help you examine the contents of a class, retrieve the source code of a method, extract and format the argument list for a function, or get all the information you need to display a detailed traceback.

提交回复
热议问题