How do I look inside a Python object?

后端 未结 22 1594
感情败类
感情败类 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 04:47

    In addition if you want to look inside list and dictionaries, you can use pprint()

    0 讨论(0)
  • 2020-12-04 04:50

    While pprint has been mentioned already by others I'd like to add some context.

    The pprint module provides a capability to “pretty-print” arbitrary Python data structures in a form which can be used as input to the interpreter. If the formatted structures include objects which are not fundamental Python types, the representation may not be loadable. This may be the case if objects such as files, sockets, classes, or instances are included, as well as many other built-in objects which are not representable as Python constants.

    pprint might be in high-demand by developers with a PHP background who are looking for an alternative to var_dump().

    Objects with a dict attribute can be dumped nicely using pprint() mixed with vars(), which returns the __dict__ attribute for a module, class, instance, etc.:

    from pprint import pprint
    pprint(vars(your_object))
    

    So, no need for a loop.

    To dump all variables contained in the global or local scope simply use:

    pprint(globals())
    pprint(locals())
    

    locals() shows variables defined in a function.
    It's also useful to access functions with their corresponding name as a string key, among other usages:

    locals()['foo']() # foo()
    globals()['foo']() # foo()
    

    Similarly, using dir() to see the contents of a module, or the attributes of an object.

    And there is still more.

    0 讨论(0)
  • 2020-12-04 04:51

    Python has a strong set of introspection features.

    Take a look at the following built-in functions:

    • type()
    • dir()
    • id()
    • getattr()
    • hasattr()
    • globals()
    • locals()
    • callable()

    type() and dir() are particularly useful for inspecting the type of an object and its set of attributes, respectively.

    0 讨论(0)
  • 2020-12-04 04:51

    If you're interested in a GUI for this, take a look at objbrowser. It uses the inspect module from the Python standard library for the object introspection underneath.

    objbrowserscreenshot

    0 讨论(0)
  • 2020-12-04 04:52

    I'm surprised no one's mentioned help yet!

    In [1]: def foo():
       ...:     "foo!"
       ...:
    
    In [2]: help(foo)
    Help on function foo in module __main__:
    
    foo()
        foo!
    

    Help lets you read the docstring and get an idea of what attributes a class might have, which is pretty helpful.

    0 讨论(0)
  • 2020-12-04 04:54

    pprint and dir together work great

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