python中dump函数_python中实现php的var_dump函数功能
最近在做python的web開發(fā)(原諒我的多變,好東西總想都學(xué)著。。。node.js也是),不過過程中總遇到些問題,不管是web.py還是django,開發(fā)起來確實(shí)沒用php方便,畢竟存在的時(shí)間比較短,很多不完善的地方。
比如我在調(diào)試php中最常用的函數(shù),var_dump,在python里找不到合適的替代函數(shù)。php中var_dump是一個(gè)特別有用的函數(shù),它可以輸出任何變量的值,不管你是一個(gè)對象還是一個(gè)數(shù)組,或者只是一個(gè)數(shù)。它總能用友好的方式輸出,我調(diào)試的時(shí)候經(jīng)常會需要看某位置的變量信息,調(diào)用它就很方便:
但是開發(fā)python的時(shí)候就沒有太好的替代方案。
之前想到repr,但這個(gè)函數(shù)只是調(diào)用了對象中的__str__,和直接print obj沒啥區(qū)別。print是打印它,而repr是將其作為值返回。如果對象所屬的類沒有定義__str__這個(gè)函數(shù),那么返回的就會是難看的一串字符。
后來又想到了vars 函數(shù),vars函數(shù)是python的內(nèi)建函數(shù),專門用來輸出一個(gè)對象的內(nèi)部信息。但這個(gè)對象所屬的類中必須有__dict__函數(shù)。一般的類都有這個(gè)dict,但像[]和{}等對象就不存在這個(gè)dict,這樣調(diào)用vars函數(shù)就會拋出一個(gè)異常:
Traceback (most recent call last):
File "", line 1, in
TypeError: vars() argument must have __dict__ attribute
所以后來幾經(jīng)尋找,找到一個(gè)個(gè)比較好,功能能夠與var_dump類似的函數(shù)如下:
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
這是使用方式:
class stdClass(object): pass
obj=stdClass()
obj.int=1
obj.tup=(1,2,3,4)
obj.dict={'a':1,'b':2, 'c':3, 'more':{'z':26,'y':25}}
obj.list=[1,2,3,'a','b','c',[1,2,3,4]]
obj.subObj=stdClass()
obj.subObj.value='foobar'
from pprint import pprint
pprint(dump(obj))
最后輸出是:
{'__type__': '<__main__.stdclass object at>',
'dict': {'a': 1, 'c': 3, 'b': 2, 'more': {'y': 25, 'z': 26}},
'int': 1,
'list': [1, 2, 3, 'a', 'b', 'c', [1, 2, 3, 4]],
'subObj': {'__type__': '<__main__.stdclass object at>',
'value': 'foobar'},
'tup': (1, 2, 3, 4)}
然后github有個(gè)開源的module,可以參考:https://github.com/sha256/python-var-dump
說一下pprint這個(gè)函數(shù),他是一個(gè)人性化輸出的函數(shù),會將要輸出的內(nèi)容用程序員喜歡的方式輸出在屏幕上。參閱這篇文章比較好理解://www.zyiz.net/article/60143.htm
總結(jié)
以上是生活随笔為你收集整理的python中dump函数_python中实现php的var_dump函数功能的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: macos ntfs插件_Mac下NTF
- 下一篇: frp+nginx实现内网穿透