How do I look inside a Python object?

后端 未结 22 1597
感情败类
感情败类 2020-12-04 04:18

I\'m starting to code in various projects using Python (including Django web development and Panda3D game development).

To help me understand what\'s going on, I wo

相关标签:
22条回答
  • 2020-12-04 05:00

    You can list the attributes of a object with dir() in the shell:

    >>> dir(object())
    ['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
    

    Of course, there is also the inspect module: http://docs.python.org/library/inspect.html#module-inspect

    0 讨论(0)
  • 2020-12-04 05:00

    Many good tipps already, but the shortest and easiest (not necessarily the best) has yet to be mentioned:

    object?
    
    0 讨论(0)
  • 2020-12-04 05:02

    Try ppretty

    from ppretty import ppretty
    
    
    class A(object):
        s = 5
    
        def __init__(self):
            self._p = 8
    
        @property
        def foo(self):
            return range(10)
    
    
    print ppretty(A(), indent='    ', depth=2, width=30, seq_length=6,
                  show_protected=True, show_private=False, show_static=True,
                  show_properties=True, show_address=True)
    

    Output:

    __main__.A at 0x1debd68L (
        _p = 8, 
        foo = [0, 1, 2, ..., 7, 8, 9], 
        s = 5
    )
    
    0 讨论(0)
  • 2020-12-04 05:02

    There is a python code library build just for this purpose: inspect Introduced in Python 2.7

    0 讨论(0)
  • 2020-12-04 05:02

    vars(obj) returns the attributes of an object.

    0 讨论(0)
  • 2020-12-04 05:06

    Others have already mentioned the dir() built-in which sounds like what you're looking for, but here's another good tip. Many libraries -- including most of the standard library -- are distributed in source form. Meaning you can pretty easily read the source code directly. The trick is in finding it; for example:

    >>> import string
    >>> string.__file__
    '/usr/lib/python2.5/string.pyc'
    

    The *.pyc file is compiled, so remove the trailing 'c' and open up the uncompiled *.py file in your favorite editor or file viewer:

    /usr/lib/python2.5/string.py
    

    I've found this incredibly useful for discovering things like which exceptions are raised from a given API. This kind of detail is rarely well-documented in the Python world.

    0 讨论(0)
提交回复
热议问题