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

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

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


当前回答

你可以在shell中使用dir()列出对象的属性:

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

当然,还有inspect模块:http://docs.python.org/library/inspect.html#module-inspect

其他回答

此外,如果您想查看列表和字典内部,可以使用pprint()

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

有一个很酷的工具叫objexplore。下面是一个简单的例子,关于如何在pandas数据框架上使用它的探索功能。

import pandas as pd
df=pd.read_csv('https://storage.googleapis.com/download.tensorflow.org/data/heart.csv')

from objexplore import explore
explore(df)

将在你的shell中弹出以下内容:

在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"}

其他人已经提到了dir()内置,这听起来像是您正在寻找的,但这里有另一个很好的提示。许多库——包括大多数标准库——都是以源代码形式发布的。这意味着您可以很容易地直接阅读源代码。诀窍在于找到它;例如:

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

*。Pyc文件已编译,因此删除后面的'c',并在您最喜欢的编辑器或文件查看器中打开未编译的*.py文件:

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

我发现这对于发现从给定API引发哪些异常等事情非常有用。这种细节在Python世界中很少有良好的文档。