Python 中的var_dump, 对象打印

var_dump 是PHP中的调试函数,可以用var_dump打印所有的对象。查看对象内部的数据结构,对调试非常有用。

python 中可以使用print str(object)这种方式打印对象内容,但是前提是类已经定义了__str__函数。如果没有定义那就没办法了。

今天找到两种替代方案标记一下。


1.

from pprint import pprint

pprint(dump(obj))

def dump(obj):
  '''return a printable representation of an object for debugging'''
  newobj=obj
  if '__dict__' in dir(obj):
    newobj=obj.__dict__
    if ' object at ' in str(obj) and not newobj.has_key('__type__'):
      newobj['__type__']=str(obj)
    for attr in newobj:
      newobj[attr]=dump(newobj[attr])
  return newobj


2, git hub 上的一个模块

https://github.com/sha256/python-var-dump

猜你喜欢

转载自blog.csdn.net/abccheng/article/details/61202648