How do I look inside a Python object?

后端 未结 22 1596
感情败类
感情败类 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:55

    If you want to look inside a live object, then python's inspect module is a good answer. In general, it works for getting the source code of functions that are defined in a source file somewhere on disk. If you want to get the source of live functions and lambdas that were defined in the interpreter, you can use dill.source.getsource from dill. It also can get the code for from bound or unbound class methods and functions defined in curries... however, you might not be able to compile that code without the enclosing object's code.

    >>> from dill.source import getsource
    >>> 
    >>> def add(x,y):
    ...   return x+y
    ... 
    >>> squared = lambda x:x**2
    >>> 
    >>> print getsource(add)
    def add(x,y):
      return x+y
    
    >>> print getsource(squared)
    squared = lambda x:x**2
    
    >>> 
    >>> class Foo(object):
    ...   def bar(self, x):
    ...     return x*x+x
    ... 
    >>> f = Foo()
    >>> 
    >>> print getsource(f.bar)
    def bar(self, x):
        return x*x+x
    
    >>> 
    
    0 讨论(0)
  • 2020-12-04 04:57

    Try using:

    print(object.stringify())
    
    • where object is the variable name of the object you are trying to inspect.

    This prints out a nicely formatted and tabbed output showing all the hierarchy of keys and values in the object.

    NOTE: This works in python3. Not sure if it works in earlier versions

    UPDATE: This doesn't work on all types of objects. If you encounter one of those types (like a Request object), use one of the following instead:

    • dir(object())

    or

    import pprint then: pprint.pprint(object.__dict__)

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

    Two great tools for inspecting code are:

    1. IPython. A python terminal that allows you to inspect using tab completion.

    2. Eclipse with the PyDev plugin. It has an excellent debugger that allows you to break at a given spot and inspect objects by browsing all variables as a tree. You can even use the embedded terminal to try code at that spot or type the object and press '.' to have it give code hints for you.

    0 讨论(0)
  • 2020-12-04 04:58
    import pprint
    
    pprint.pprint(obj.__dict__)
    

    or

    pprint.pprint(vars(obj))
    
    0 讨论(0)
  • 2020-12-04 04:59

    If you are interested to see the source code of the function corresponding to the object myobj, you can type in iPython or Jupyter Notebook:

    myobj??

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

    object.__dict__

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