Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/359.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python hasattr()抛出AttributeError_Python_Django - Fatal编程技术网

Python hasattr()抛出AttributeError

Python hasattr()抛出AttributeError,python,django,Python,Django,我试图检查django应用程序中的某些xml是否具有某些元素/节点,如果不只是跳过该代码块。我正在使用hasattr()检查元素是否存在,如果元素不存在,它将返回false: 如果hasattr(product.itemtattributes,'ListPrice')\和hasattr(product.Offers.Offer.OfferListing,'PercentageSaved')\ 和hasattr(product.LargeImage,'URL'): 但在我的例子中,它抛出了一个属性

我试图检查django应用程序中的某些xml是否具有某些元素/节点,如果不只是跳过该代码块。我正在使用hasattr()检查元素是否存在,如果元素不存在,它将返回false:

如果hasattr(product.itemtattributes,'ListPrice')\和hasattr(product.Offers.Offer.OfferListing,'PercentageSaved')\
和hasattr(product.LargeImage,'URL'):

但在我的例子中,它抛出了一个属性错误:
AttributeError at/update\u产品/
没有这类儿童:{http://webservices.amazon.com/AWSECommerceService/2011-08-01}大图像


我不明白为什么它会抛出一个错误,而不是仅仅返回false并让我跳过代码块?

这个错误是因为
图像太大。这是由以下表达式引起的:
product.LargeImage
。您可能希望首先检查该错误,或者更好地将其放入
try/except
块中。

错误是由于
LargeImage
。这是由以下表达式引起的:
product.LargeImage
。您可能希望首先检查该属性,或者更好地将其放入
try/except
块。

也许
product.itemtattributes
product.Offers.OfferListing
product.LargeImage
中的一个不存在?最有可能是
product.LargeImage
。可能是
product.ItemAttributes
product.Offers.offerList
product.LargeImage
中的一个不存在?最有可能是
product.LargeImage
。啊,我没有意识到hasattr依赖于现有的父属性。我刚刚输入了您的答案,解决了我的问题,但随后给了我一个新问题,即知道目标元素是否存在,而不必检查它的父元素是否存在。不过,我认为您关于
try/except
块的最新答案是正确的,谢谢@KingFu
hasattr
不依赖于现有的父属性。如果不调用任何
hasattr
,就会发生此错误。问题是有一个表达式试图引用一个不存在的属性。我明白了,我基本上是想传递一个不存在的对象。谢谢你的补充评论,我没有意识到hasattr依赖于现有的父属性。我刚刚输入了您的答案,解决了我的问题,但随后给了我一个新问题,即知道目标元素是否存在,而不必检查它的父元素是否存在。不过,我认为您关于
try/except
块的最新答案是正确的,谢谢@KingFu
hasattr
不依赖于现有的父属性。如果不调用任何
hasattr
,就会发生此错误。问题是有一个表达式试图引用一个不存在的属性。我明白了,我基本上是想传递一个不存在的对象。谢谢你的补充意见,为我澄清这一点