python - python中对象没有属性错误

标签 python oop linked-list attributeerror

我是 python 编程新手,我遇到了下面提到的程序的错误。这是一个简单的程序,用于将一个节点添加到链表的末尾。该错误表明对象 LinkedList 没有属性头。请帮我解决这个问题。

class Node:
    def _init_(self, data):
        self.data = data
        self.next = None

class LinkedList:
    def _init_(self):
        self.head=None

    def createNode(self, data):
        newNode = Node(data)
        return newNode

    def insertNodeHelper(self, head, data):
        if(head==None):
            return self.createNode(data)
        head.next = self.insertNodeHelper(head.next,data)
        return head

    def insertNode(self, data):
        self.head = self.insertNodeHelper(self.head,data)

    def printList(self, head):
        if(head==None):
            return;
        print(head.data)
        self.printList(head.next)

    def printLinkedList(self):
        self.printList(self.head)

l = LinkedList()
l.insertNode(12)
l.insertNode(13)
l.insertNode(15)
l.printList()

我收到以下错误:

Message File Name   Line    Position    
Traceback               
    <module>    <module1>   35      
    insertNode  <module1>   21      
AttributeError: 'LinkedList' object has no attribute 'head'             

最佳答案

def __init__(self): 更改为 def __init__(self):(两个下划线)。因为这个方法是构造函数方法,所以必须写成这种形式。

关于python - python中对象没有属性错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49271771/

相关文章:

python - 如何计算函数最坏情况的复杂度?

javascript - 如何创建 Javascript Function 类的子类?

javascript - 在 JavaScript 类函数中使用 setTimeout()

javascript - 在事件处理程序上使用 bind(this)

javascript - 分割链表

c - 在链表中插入字符串时出现问题

python - 如何将 object.__dict__ 再次转换为对象本身?

python - 使用 Web 套接字和 Gunicorn 运行 Flask 应用程序时出错

java - 为什么数组列表比后进先出行为的链表更快?

python - Python 网络爬虫的文件存储问题