是否有内置函数来打印对象的所有当前属性和值? [英] Is there a built-in function to print all the current properties and values of an object?
本文介绍了是否有内置函数来打印对象的所有当前属性和值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我在这里寻找的是类似于 PHP 的 print_r 函数.
这样我就可以通过查看相关对象的状态来调试我的脚本.
解决方案
你真的把两种不同的东西混在一起了.
使用dir()
,vars()
或 inspect
模块以获取您感兴趣的内容(我使用 __builtins__
作为示例;您可以使用任何对象代替).
打印你喜欢的字典:
<预><代码>>>>打印 l['ArithmeticError', 'AssertionError', 'AttributeError',...或
<预><代码>>>>从 pprint 导入 pprint>>>打印(l)['算术错误','断言错误','属性错误','基础异常','弃用警告',...>>>pprint(d,缩进= 2){ 'ArithmeticError': <type 'exceptions.ArithmeticError'>,'AssertionError':在交互式调试器中也可以通过命令进行漂亮的打印:
(Pdb) pp vars(){'__builtins__': {'ArithmeticError': <type 'exceptions.ArithmeticError'>,'AssertionError': ,'AttributeError': ,'BaseException': ,'BufferError': ,...'zip': <内置函数 zip>},'__file__': 'pass.py','__name__': '__main__'}
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.
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 that dictionary however fancy you like:
>>> 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 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屋!
查看全文