Python 属性错误:';非类型';对象没有属性'';
我在Python中使用双链接列表时遇到以下错误:Python 属性错误:';非类型';对象没有属性'';,python,nonetype,Python,Nonetype,我在Python中使用双链接列表时遇到以下错误: def merge(self,other): mergedCenter = HealthCenter() selfPatient = self._head otherPatient = other._head print(selfPatient.elem) print(selfPatient.elem < otherPatient.elem)
def merge(self,other):
mergedCenter = HealthCenter()
selfPatient = self._head
otherPatient = other._head
print(selfPatient.elem)
print(selfPatient.elem < otherPatient.elem)
while (selfPatient or otherPatient):
if selfPatient.elem < otherPatient.elem:
mergedCenter.addLast(selfPatient.elem)
selfPatient = selfPatient.next
elif selfPatient.elem > otherPatient.elem:
mergedCenter.addLast(otherPatient.elem)
otherPatient = otherPatient.next
else:
mergedCenter.addLast(selfPatient.elem)
selfPatient = selfPatient.next
otherPatient = otherPatient.next
return (mergedCenter)
def合并(自身、其他):
mergedCenter=HealthCenter()
自我病人=自我
其他患者=其他。\头部
打印(selfPatient.elem)
打印(selfPatient.elemotherPatient.elem:
mergedCenter.addLast(otherPatient.elem)
otherPatient=otherPatient.next
其他:
mergedCenter.addLast(selfPatient.elem)
selfPatient=selfPatient.next
otherPatient=otherPatient.next
返回(合并中心)
我得到这个输出:
Abad, Ana 1949 True 0
True
Traceback (most recent call last):
File "main.py", line 189, in <module>
hc3 = hc1.merge(hc2)
File "main.py", line 112, in merge
if selfPatient.elem < otherPatient.elem:
AttributeError: 'NoneType' object has no attribute 'elem'
Abad,Ana 1949真0
真的
回溯(最近一次呼叫最后一次):
文件“main.py”,第189行,在
hc3=hc1.合并(hc2)
文件“main.py”,第112行,合并
如果selfPatient.elem
已经实现了一个方法来比较.elem,正如您在第二次打印中可以清楚地看到的,但是我不明白为什么在第一次打印中它不断中断
提前谢谢
解决方案:
必须考虑两个数据列表的长度,而不是两个值中的一个“Nonetype”。这可以通过更改AND的OR来解决,然后检查哪一个不是“非类型”来完成合并这将检查其中一个是否为非无,因此如果一个是,而不是另一个,则进入循环
while (selfPatient or otherPatient)
如果要访问两个元素
属性,则这两个属性都必须是非None,需要将或
更改为和
否则,在if语句之前需要单独的逻辑来处理只有一个是None的情况,然后可能会中断循环以达到返回。如果selfPatient和otherPatient都使用属性,那么将现有逻辑的其余部分封装在中也不会有什么坏处
至于为什么一个变为无,这取决于您在某个点迭代链表的逻辑。下一个
调用返回的是NoneselfPatient
或otherPatient
为None。您的while条件仅检查是否至少有一个节点不是无。使用和
而不是或
来检查两者。请提供预期的值。显示中间结果与预期结果的偏差。我们应该能够将单个代码块粘贴到文件中,运行它,并重现您的问题。这也让我们可以在您的上下文中测试任何建议。我们希望您至少查找错误消息,并尝试在程序中跟踪有问题的值。完全正确。然后我应该检查selfPatient或otherPatient是否为None,并完成合并。谢谢大家