鉴于以下通用代码:
def soapQuery():
soapuser = "Base64String"
soappass = "Base64String"
soapurl = 'https://url/file.ext?wsdl'
ntlm = WindowsHttpAuthenticated(username=soapuser, password=soappass)
client = Client(soapurl, transport=ntlm)
result = client.service.method(something='somethingtosearchfor')
soapfiltered = []
for record in result.SoapRecord:
soapfiltered.extend((str(record.value1), str(record.value2), str(record.value3), str(record.value4)))
return zip(*[iter(soapfiltered)]*4)当运行时,我得到以下错误:
AttributeError: SoapRecord实例没有属性“value3”
result.SoapRecord返回的大部分内容将包含所有4record.value,但有些则没有。有办法像None或Null那样设置默认值吗?我尝试过将record.setdefault('value3', None)放入其中,但不起作用。如果能提供任何和所有的帮助,我们将不胜感激。谢谢。
发布于 2015-04-02 06:33:26
嗯,Python中没有Null,而setdefault的默认设置是None。顺便说一句,不能通过Python中的点运算符访问字典(遗憾的是,我错过了JS的特性),所以基本上……我不认为record是字典,而是一个对象。要检查对象是否有属性,可以做hasattr(record, 'value1')。
考虑到这一点,为了将所有内容保持在一个表达式中,您可以这样做:
hasattr(record, 'value1') and str(record.value1) or None
这是一个布尔表达式,在Python中,您可以计算布尔表达式,而无需将值完全转换为bools。因此,该表达式将为您提供str(record.value1)的值或简单的None。
对不起,如果这个答案有什么错误的话,我不熟悉Soap库。
编辑: As @plaes在评论中指出,getattr(record, 'value1', None)是一种更短、更容易实现的方式。谢谢你的编曲:)
https://stackoverflow.com/questions/29406226
复制相似问题