鉴于此代码:
class XmlObj(dict):
def __init__(self,xml,*args,**kwargs):
super(dict,self).__init__(*args,**kwargs)
if xml.firstChild.nodeName == '#text':
self.__setattr__( 'text', xml.firstChild.nodeValue )
return
else:
for node in xml.childNodes:
if self.has_key( node.nodeName ):
item = self.__getitem__(node.nodeName)
if type( item ) is not type( [] ):
item = [item]
item.append( XmlObj( node ))
self.__setitem__(node.nodeName, item )
else:
self.__setitem__(node.nodeName, XmlObj(node) )
def __str__(self):
if hasattr(self,'text'):
return self.__getattribute__('text')
else:
return "%s"%super(dict,self).__str__()
text = """<?xml version="1.0"?><response><success>true</success><message>Metric List</message><page>1</page><rpp>50</rpp><total>9</total><pages>1</pages></response>"""
obj = XmlObj( parseString( text ).documentElement )
print obj
print obj['rpp']
>>> {u'rpp': {}, u'success': {}, u'pages': {}, u'message': {}, u'total': {}, u'page': {}}
>>> 50
我想得到:
>>> {u'rpp': '50', u'success': True, u'pages': 4, u'message': 'Some message', u'total': 90, u'page': 1}
我只是想知道Python如何处理对象的__repr__
调用只是为了获取obj参数,而不是显示text
属性而不是空字典。
答案 0 :(得分:1)
在一些谷歌搜索终于找到答案后,只是为了提供信息,我将在这里发布答案
http://effbot.org/pyfaq/how-can-i-get-a-dictionary-to-display-its-keys-in-a-consistent-order.htm
class XmlObj(dict):
def __init__(self,xml,*args,**kwargs):
super(dict,self).__init__(*args,**kwargs)
if xml.firstChild.nodeName == '#text':
self.__setattr__( 'text', xml.firstChild.nodeValue )
return
else:
for node in xml.childNodes:
if self.has_key( node.nodeName ):
item = self.__getitem__(node.nodeName)
if type( item ) is not type( [] ):
item = [item]
item.append( XmlObj( node ))
self.__setitem__(node.nodeName, item )
else:
self.__setitem__(node.nodeName, XmlObj(node) )
def __repr__(self):
if hasattr(self,'text'):
return self.__getattribute__('text')
else:
result = ["%r: %r" % (key, self[key]) for key in sorted(self)]
return "{" + ", ".join(result) + "}"
__str__ = __repr__
不管怎样,谢谢大家:)