chanakya sunkarapally
chanakya sunkarapally

Reputation: 69

object has no attribute error in python

I am new to python programming and I have encountered an error for the below mentioned program. It is a simple program to add a node to the end of the linked list. The error says object LinkedList has no attribute head. Please Help me with the problem.

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()

I am getting the following error:

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

Upvotes: 1

Views: 783

Answers (1)

黄煜楠
黄煜楠

Reputation: 64

Change def _init_(self): to def __init__(self):(two underscore). Because this method is a constructor method, it must be writen in this form.

Upvotes: 4

Related Questions