这里我要找的是PHP的print_r函数。
这样我就可以通过查看有问题的对象的状态来调试脚本。
这里我要找的是PHP的print_r函数。
这样我就可以通过查看有问题的对象的状态来调试脚本。
当前回答
如果你用它来调试,你只是想递归转储所有的东西,接受的答案是不令人满意的,因为它要求你的类已经有良好的__str__实现。如果不是这样的话,这样做会更好:
import json
print(json.dumps(YOUR_OBJECT,
default=lambda obj: vars(obj),
indent=1))
其他回答
尝试ppretty
from ppretty import ppretty
class A(object):
s = 5
def __init__(self):
self._p = 8
@property
def foo(self):
return range(10)
print ppretty(A(), show_protected=True, show_static=True, show_properties=True)
输出:
__main__.A(_p = 8, foo = [0, 1, ..., 8, 9], s = 5)
你需要vars()和pprint()的混合:
from pprint import pprint
pprint(vars(your_object))
试试beeprint吧。
它不仅可以帮助你打印对象变量,还可以帮助你输出漂亮的结果,就像这样:
class(NormalClassNewStyle):
dicts: {
},
lists: [],
static_props: 1,
tupl: (1, 2)
从答案中,可以稍微修改一下,只得到一个对象的“Attributes”,如下所示:
def getAttributes(obj):
from pprint import pprint
from inspect import getmembers
from types import FunctionType
def attributes(obj):
disallowed_names = {
name for name, value in getmembers(type(obj))
if isinstance(value, FunctionType)}
return {
name for name in dir(obj)
if name[0] != '_' and name not in disallowed_names and hasattr(obj, name)}
pprint(attributes(obj))
在临时添加此函数时非常有用,并且可以在不修改现有源代码的情况下删除此函数
你实际上是把两种不同的东西混合在一起。
使用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__'}