Python中是否有函数来打印对象的所有当前属性和值? [英] Is there a function in Python to print all the current properties and values of an object?

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

问题描述

所以我正在寻找的是 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() 检查 模块以获取您感兴趣的内容(我以 __ 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 that dictionary however fancy you like:

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

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

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