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

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

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


当前回答

import pprint

pprint.pprint(obj.__dict__)

or

pprint.pprint(vars(obj))

其他回答

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

如果您正在寻找一个稍微更微妙的解决方案,您可以尝试objprint。它的一个积极的方面是它可以处理嵌套对象。例如:

from objprint import objprint

class Position:
    def __init__(self, x, y):
        self.x = x
        self.y = y

class Player:
    def __init__(self):
        self.name = "Alice"
        self.age = 18
        self.items = ["axe", "armor"]
        self.coins = {"gold": 1, "silver": 33, "bronze": 57}
        self.position = Position(3, 5)

objprint(Player())

会打印出来

<Player
  .name = 'Alice',
  .age = 18,
  .items = ['axe', 'armor'],
  .coins = {'gold': 1, 'silver': 33, 'bronze': 57},
  .position = <Position
    .x = 3,
    .y = 5
  >
>

首先,阅读原文。

其次,使用dir()函数。

你可以在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或dir()

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

object.__dict__