这里我要找的是PHP的print_r函数。
这样我就可以通过查看有问题的对象的状态来调试脚本。
这里我要找的是PHP的print_r函数。
这样我就可以通过查看有问题的对象的状态来调试脚本。
当前回答
Vars()似乎显示了该对象的属性,但dir()似乎也显示了父类(es)的属性。您通常不需要看到继承的属性,如str, doc。dict等等。
In [1]: class Aaa():
...: def __init__(self, name, age):
...: self.name = name
...: self.age = age
...:
In [2]: class Bbb(Aaa):
...: def __init__(self, name, age, job):
...: super().__init__(name, age)
...: self.job = job
...:
In [3]: a = Aaa('Pullayya',42)
In [4]: b = Bbb('Yellayya',41,'Cop')
In [5]: vars(a)
Out[5]: {'name': 'Pullayya', 'age': 42}
In [6]: vars(b)
Out[6]: {'name': 'Yellayya', 'age': 41, 'job': 'Cop'}
In [7]: dir(a)
Out[7]:
['__class__',
'__delattr__',
'__dict__',
'__dir__',
'__doc__',
'__eq__',
...
...
'__subclasshook__',
'__weakref__',
'age',
'name']
其他回答
你实际上是把两种不同的东西混合在一起。
使用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__'}
我需要在一些日志中打印调试信息,无法使用pprint,因为它会破坏它。相反,我这样做了,得到了几乎相同的结果。
DO = DemoObject()
itemDir = DO.__dict__
for i in itemDir:
print '{0} : {1}'.format(i, itemDir[i])
虽然有很多好的答案,这里有一个一行程序,可以给出属性和值:
(str(vars(config)).split(",")[1:])
其中'config'是有问题的对象。我列出这作为一个单独的答案,因为我只是想简单地打印对象的相关值(包括__main等),而不使用循环或漂亮的打印,没有找到一个方便的答案。
尝试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)
这将以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)