是否有内置功能可以打印对象的所有当前属性和值? [英] Is there a built-in function to print all the current properties and values of an object?

查看:72
本文介绍了是否有内置功能可以打印对象的所有当前属性和值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

So what I'm looking for here is something like PHP's print_r function.

因此,我可以通过查看问题对象的状态来调试脚本。

This is so I can debug my scripts by seeing what's the state of the object in question.

推荐答案

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

You are really mixing together two different things.

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

Use dir(), vars() or the inspect module to get what you are interested in (I use __builtins__ as an example; you can use any object instead).

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

在交互式调试器中还可以通过以下命令获得漂亮的打印效果:

Pretty printing is also available in the interactive debugger as a command:

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

这篇关于是否有内置功能可以打印对象的所有当前属性和值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆