我开始使用Python编写各种项目的代码(包括Django web开发和Panda3D游戏开发)。

为了帮助我理解发生了什么,我想基本上“看看”Python对象内部,看看它们是如何运行的——比如它们的方法和属性。

假设我有一个Python对象,我需要什么来打印它的内容?这可能吗?


当前回答

在Python 3.8中,你可以使用__dict__. __dict__来打印对象的内容。例如,

class Person():
   pass

person = Person()

## set attributes
person.first = 'Oyinda'
person.last = 'David'

## to see the content of the object
print(person.__dict__)  

{"first": "Oyinda", "last": "David"}

其他回答

尝试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)

输出:

__main__.A at 0x1debd68L (
    _p = 8, 
    foo = [0, 1, 2, ..., 7, 8, 9], 
    s = 5
)

Python有一组强大的自省特性。

看看下面的内置函数:

(型) dir () (id) getattr () hasattr () globals () locals () callable ()

Type()和dir()分别对于检查对象的类型及其属性集特别有用。

如果您想查看参数和方法,就像其他人指出的那样,可以使用pprint或dir()

如果您想查看内容的实际值,可以这样做

object.__dict__

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

>>> 
import pprint

pprint.pprint(obj.__dict__)

or

pprint.pprint(vars(obj))