这里我要找的是PHP的print_r函数。

这样我就可以通过查看有问题的对象的状态来调试脚本。


当前回答

要打印对象的当前状态,你可以:

>>> obj # in an interpreter

or

print repr(obj) # in a script

or

print obj

为你的类定义__str__或__repr__方法。来自Python文档:

__repr__(self)由repr()内置函数调用,由字符串调用 转换(反引号)到 计算“官方”字符串 对象的表示。如果有的话 可能,这看起来像a 有效的Python表达式 方法重新创建对象 相同的值(给定一个合适的 环境)。如果不可能, 形式为“<…一些有用的 描述……应该返回>。 返回值必须为字符串 对象。如果一个类定义了repr() 但不是__str__(),则__repr__()是 也用于“非正式”字符串 实例的表示 班级是必需的。这是典型的 用于调试,所以很重要 这个表示是 信息丰富且明确。 __str__(self)由str()内置函数调用,由print函数调用 语句来计算“非正式的” 对象的字符串表示形式。 这与__repr__()不同 它不必是一个有效的Python 表达:比较方便还是 可以使用简洁的表示 代替。返回值必须为a 字符串对象。

其他回答

从答案中,可以稍微修改一下,只得到一个对象的“Attributes”,如下所示:

def getAttributes(obj):
    from pprint import pprint
    from inspect import getmembers
    from types import FunctionType
    
    def attributes(obj):
        disallowed_names = {
          name for name, value in getmembers(type(obj)) 
            if isinstance(value, FunctionType)}
        return {
          name for name in dir(obj) 
            if name[0] != '_' and name not in disallowed_names and hasattr(obj, name)}
    pprint(attributes(obj))

在临时添加此函数时非常有用,并且可以在不修改现有源代码的情况下删除此函数

你可以使用"dir()"函数来做到这一点。

>>> import sys
>>> dir(sys)
['__displayhook__', '__doc__', '__excepthook__', '__name__', '__stderr__', '__stdin__', '__stdo
t__', '_current_frames', '_getframe', 'api_version', 'argv', 'builtin_module_names', 'byteorder
, 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dllhandle', 'exc_clear', 'exc_info'
 'exc_type', 'excepthook', 'exec_prefix', 'executable', 'exit', 'getcheckinterval', 'getdefault
ncoding', 'getfilesystemencoding', 'getrecursionlimit', 'getrefcount', 'getwindowsversion', 'he
version', 'maxint', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_
ache', 'platform', 'prefix', 'ps1', 'ps2', 'setcheckinterval', 'setprofile', 'setrecursionlimit
, 'settrace', 'stderr', 'stdin', 'stdout', 'subversion', 'version', 'version_info', 'warnoption
', 'winver']
>>>

另一个有用的功能是帮助。

>>> help(sys)
Help on built-in module sys:

NAME
    sys

FILE
    (built-in)

MODULE DOCS
    http://www.python.org/doc/current/lib/module-sys.html

DESCRIPTION
    This module provides access to some objects used or maintained by the
    interpreter and to functions that interact strongly with the interpreter.

    Dynamic objects:

    argv -- command line arguments; argv[0] is the script pathname if known

你实际上是把两种不同的东西混合在一起。

使用dir(), vars()或inspect模块来获取您感兴趣的内容(我使用__builtins__作为示例;你可以用任何物体代替)。

>>> l = dir(__builtins__)
>>> d = __builtins__.__dict__

随你喜欢,把那本词典打印出来吧:

>>> print l
['ArithmeticError', 'AssertionError', 'AttributeError',...

or

>>> from pprint import pprint
>>> pprint(l)
['ArithmeticError',
 'AssertionError',
 'AttributeError',
 'BaseException',
 'DeprecationWarning',
...

>>> pprint(d, indent=2)
{ 'ArithmeticError': <type 'exceptions.ArithmeticError'>,
  'AssertionError': <type 'exceptions.AssertionError'>,
  'AttributeError': <type 'exceptions.AttributeError'>,
...
  '_': [ 'ArithmeticError',
         'AssertionError',
         'AttributeError',
         'BaseException',
         'DeprecationWarning',
...

Pretty print也可以在交互式调试器中作为命令使用:

(Pdb) pp vars()
{'__builtins__': {'ArithmeticError': <type 'exceptions.ArithmeticError'>,
                  'AssertionError': <type 'exceptions.AssertionError'>,
                  'AttributeError': <type 'exceptions.AttributeError'>,
                  'BaseException': <type 'exceptions.BaseException'>,
                  'BufferError': <type 'exceptions.BufferError'>,
                  ...
                  'zip': <built-in function zip>},
 '__file__': 'pass.py',
 '__name__': '__main__'}

我建议使用help(your_object)。

帮助(dir)

如果不带参数调用,则返回当前作用域中的名称。 否则,返回由(部分)属性组成的名称按字母顺序排列的列表 给定对象的属性。 如果对象提供了一个名为__dir__的方法,则将使用它;否则 使用默认的dir()逻辑并返回: 对于模块对象:模块的属性。 对于类对象:它的属性和递归的属性 它的碱基。 对于任何其他对象:它的属性,它的类的属性和 递归地获取其类的基类的属性。

帮助(变量)

不带参数,相当于locals()。 带有一个参数,等价于object.__dict__。

这将以json或yaml缩进格式递归地打印出所有对象内容:

import jsonpickle # pip install jsonpickle
import json
import yaml # pip install pyyaml

serialized = jsonpickle.encode(obj, max_depth=2) # max_depth is optional
print json.dumps(json.loads(serialized), indent=4)
print yaml.dump(yaml.load(serialized), indent=4)