为何在PyCharm中手动编写Python OOP代码会报属性错误?
解决手动输入Python双向链表代码时的属性错误问题
作为Python面向对象编程新手,在PyCharm中调用类方法时遇到问题:复制粘贴以下代码能正常运行,但手动输入相同代码时出现属性错误。
示例代码:
class Node: def __init__(self, data): self.previous = None self.data = data self.next = None class DoublyLinkedList: def __init__(self): self.head = None self.start_node = None self.last_node = None def append(self, data): if self.last_node is None: self.head = Node(data) self.last_node = self.head else: new_node = Node(data) self.last_node.next = new_node new_node.previous = self.last_node new_node.next = None self.last_node = new_node def display(self, Type): if Type == 'Left_To_Right': current = self.head while current is not None: print(current.data, end=' ') current = current.next print() else: current = self.last_node while current is not None: print(current.data, end=' ') current = current.previous print() if __name__ == '__main__': L = DoublyLinkedList() L.append(1) L.append(2) L.append(3) L.append(4) L.display('Left_To_Right') L.display('Right_To_Left')
排查与解决方法
- 检查拼写错误:重点核对所有属性名(如
previous、next、last_node)、类名(Node、DoublyLinkedList)和方法名(append、display),手动输入时极易出现字母漏写、错写(比如把previous写成previus,last_node写成lastnode)。 - 确认缩进正确性:Python依赖缩进区分代码块,检查以下部分:
append和display方法是否正确缩进在DoublyLinkedList类内部if/else分支、while循环的缩进层级是否与示例代码一致- 避免混合使用空格和Tab作为缩进(可在PyCharm设置中统一缩进规则)
- 核对大小写一致性:Python是大小写敏感语言,检查:
- 方法参数
Type的大小写(调用时传参是'Left_To_Right',不要把参数名写成type) - 字符串参数的大小写(比如不要把
'Left_To_Right'写成'left_to_right')
- 方法参数
- 检查类属性初始化:确认
DoublyLinkedList的__init__方法中,self.head、self.last_node等属性都已正确初始化为None,没有遗漏定义。 - 验证方法调用拼写:检查主程序中
L.append()、L.display()的调用是否拼写正确,比如不要把append写成appen。
内容的提问来源于stack exchange,提问作者Zulkarnain Jibril
相关产品推荐
相关产品推荐

