小编典典

是否有一个内置函数可以打印对象的所有当前属性和值?

all

所以我在这里寻找的是 PHP 的print_r函数。

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


阅读 80

收藏
2022-02-25

共1个答案

小编典典

你真的把两种不同的东西混合在一起了。

使用dir(),vars()inspect模块来获取您感兴趣的内容(我__builtins__以此为例;您可以使用任何对象代替)。

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

打印你喜欢的字典:

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

要么

>>> 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',
...

交互式调试器中也可以使用命令进行漂亮的打印:

(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__'}
2022-02-25