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

新手上路,请多包涵

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

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

原文由 fuentesjr 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 416
2 个回答

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

Use dir() , vars() or the inspect module to get what you are interested in (I use __builtins__ as an example; you can use任何对象代替)。

 >>> 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__'}

原文由 user3850 发布,翻译遵循 CC BY-SA 3.0 许可协议

你想要 vars()pprint() --- 混合:

 from pprint import pprint
pprint(vars(your_object))

原文由 Jeremy Cantrell 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题