gpt4 book ai didi

python - 为什么 bool(xml.etree.ElementTree.Element) 评估为 False?

转载 作者:IT老高 更新时间:2023-10-28 22:25:07 37 4
gpt4 key购买 nike

import xml.etree.ElementTree as ET
e = ET.Element('Brock',Role="Bodyguard")
print bool(e)

为什么 xml.etree.ElementTree.Element 被认为是 False

我知道我可以执行 if e is not None 来检查是否存在。但我强烈希望 bool(e) 返回 True

最佳答案

事实证明,如果 Element 对象没有子对象,则将其视为 False 值。

我在源代码中找到了这个:

def __nonzero__(self):
warnings.warn(
"The behavior of this method will change in future versions. "
"Use specific 'len(elem)' or 'elem is not None' test instead.",
FutureWarning, stacklevel=2
)
return len(self._children) != 0 # emulate old behaviour, for now

即使是内联评论也同意你的看法——这种行为是有问题的;)

关于python - 为什么 bool(xml.etree.ElementTree.Element) 评估为 False?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20129996/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com