译(四十六)-Python输出对象信息
如有翻译问题欢迎评论指出,谢谢。
这篇的第三个回答我看不懂,所以我换成了第四个。
Python里有内置函数能输出一个对象的属性和值吗?
fuentesjr asked:
- 我想知道 Python 有没有类似 PHP 的 print_r 函数。
- 以便我查看对象的状态来调试脚本。
Answers:
Jeremy Cantrell - vote: 1159
你需要的是
pprint()和vars()的组合:from pprint import pprint pprint(vars(your_object))user3850 - vote: 739
你弄混了两个不同的东西。
用
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':, 'AssertionError': , 'AttributeError': , ... '_': [ 'ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'DeprecationWarning', ... Pretty printing 可作为命令用在交互式调试器中:
(Pdb) pp vars() {'__builtins__': {'ArithmeticError':, 'AssertionError': , 'AttributeError': , 'BaseException': , 'BufferError': , ... 'zip': }, '__file__': 'pass.py', '__name__': '__main__'} eduffy - vote: 83
有人提到了 dir,但它只能输出属性名。如果你需要对应的值的话,可以试试 dict。
class O: def __init__ (self): self.value = 3 o = O()输出:
>>> o.__dict__ {'value': 3}
Is there a built-in function to print all the current properties and values of an object?
fuentesjr asked:
Answers:
Jeremy Cantrell - vote: 1159
You want
vars()mixed withpprint():
你需要的是pprint()和vars()的组合:from pprint import pprint pprint(vars(your_object))user3850 - vote: 739
You are really mixing together two different things.
你弄混了两个不同的东西。Use
dir(),vars()or theinspectmodule to get what you are interested in (I use__builtins__as an example; you can use any object instead).
用dir()、vars()或者inspect模块来得到你想要的(我用__builtins__来举例子,你可以用其它对象代替)。>>> 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':, 'AssertionError': , 'AttributeError': , ... '_': [ 'ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'DeprecationWarning', ... Pretty printing is also available in the interactive debugger as a command:
Pretty printing 可作为命令用在交互式调试器中:(Pdb) pp vars() {'__builtins__': {'ArithmeticError':, 'AssertionError': , 'AttributeError': , 'BaseException': , 'BufferError': , ... 'zip': }, '__file__': 'pass.py', '__name__': '__main__'} eduffy - vote: 83
dir has been mentioned, but that\'ll only give you the attributes\' names. If you want their values as well try dict.
有人提到了 dir,但它只能输出属性名。如果你需要对应的值的话,可以试试 dict。class O: def __init__ (self): self.value = 3 o = O()Here is the output:
输出:>>> o.__dict__ {'value': 3}


共有 0 条评论