这里我要找的是PHP的print_r函数。
这样我就可以通过查看有问题的对象的状态来调试脚本。
这里我要找的是PHP的print_r函数。
这样我就可以通过查看有问题的对象的状态来调试脚本。
当前回答
这将以json或yaml缩进格式递归地打印出所有对象内容:
import jsonpickle # pip install jsonpickle
import json
import yaml # pip install pyyaml
serialized = jsonpickle.encode(obj, max_depth=2) # max_depth is optional
print json.dumps(json.loads(serialized), indent=4)
print yaml.dump(yaml.load(serialized), indent=4)
其他回答
你需要vars()和pprint()的混合:
from pprint import pprint
pprint(vars(your_object))
我建议使用help(your_object)。
帮助(dir)
如果不带参数调用,则返回当前作用域中的名称。 否则,返回由(部分)属性组成的名称按字母顺序排列的列表 给定对象的属性。 如果对象提供了一个名为__dir__的方法,则将使用它;否则 使用默认的dir()逻辑并返回: 对于模块对象:模块的属性。 对于类对象:它的属性和递归的属性 它的碱基。 对于任何其他对象:它的属性,它的类的属性和 递归地获取其类的基类的属性。
帮助(变量)
不带参数,相当于locals()。 带有一个参数,等价于object.__dict__。
你实际上是把两种不同的东西混合在一起。
使用dir(), vars()或inspect模块来获取您感兴趣的内容(我使用__builtins__作为示例;你可以用任何物体代替)。
>>> l = dir(__builtins__)
>>> d = __builtins__.__dict__
随你喜欢,把那本词典打印出来吧:
>>> 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 print也可以在交互式调试器中作为命令使用:
(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__'}
已经提到了Dir,但它只提供属性的名称。如果你也想要它们的值,试试__dict__。
class O:
def __init__ (self):
self.value = 3
o = O()
输出如下:
>>> o.__dict__
{'value': 3}
无论你的变量在类中是如何定义的,在__init__内部还是外部,这都是有效的。
your_obj = YourObj()
attrs_with_value = {attr: getattr(your_obj, attr) for attr in dir(your_obj)}