2010-08-24 63 views

回答

13

使用inspect模块

getmembers属性将返回(key, value)元组的列表。它从obj.__dict__得到的值(如果可用)并且使用getattr如果obj.__dict__中没有对应的条目。它可以帮你避免为此写几行代码。

6

更新

有更好的方法来做到这一点比dir。查看其他答案。

原来的答案

使用内置的功能dir(fp)看到fp属性。

+0

非常感谢你,现在我可以通过这些循环并打印'key = object [value]'(key = value)。有没有更好的办法? – 2010-08-24 05:17:42

+0

我想不出另一种方式,期望可能'getattr',另一种内置函数。 – 2010-08-24 05:19:30

+1

参见'inspect'模块。 – aaronasterling 2010-08-24 05:29:31

16

如果你想转储整个对象,你可以使用pprint模块来获得它的一个漂亮的版本。

from pprint import pprint 

pprint(my_object) 

# If there are many levels of recursion, and you don't want to see them all 
# you can use the depth parameter to limit how many levels it goes down 
pprint(my_object, depth=2) 

编辑:我可能误解你的“对象”是什么意思 - 如果你想看看类的实例,而不是像类型的字典基本的数据结构,你可能想看看inspect模块代替。

0

我很惊讶没有人提到过Python的__str__方法,它提供了一个对象的字符串表示。不幸的是,它似乎没有在pdb中自动打印。

对此,也可以使用__repr__,但__repr__有其他要求:一方面,您需要能够eval()的输出__repr__

相关问题