object has no attribute error in python - 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'

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

Related

Linked List Implementation Error In Python

So I was trying to make a Linked List in python, but I'm getting this error:
If currentNode.nextNode is None:
AttributeError: 'str' object has no attribute 'nextNode'
Not sure why I get that as currentNode.nextNode should have a .nextNode attribute just like every other node.
Here's the code:
class linkedListNode:
def __init__(self, value, nextNode=None):
self.value=value
self.nextNode=nextNode
class linkedList():
def __init__(self, head=None):
self.head=head
def insert(self, value):
node=linkedListNode(value)
if self.head==None:
self.head=node
return
currentNode = self.head
while True:
if currentNode.nextNode is None:
currentNode.nextNode=node
break
currentNode = currentNode.nextNode
def printLinkedList (self):
curNode=self.head
while curNode!=None:
print(curNode.value)
curNode=curNode.nextNode
#Just testing out the linked list below to see if it works:
ll=linkedList("10")
ll.insert("50")
ll.insert(4)
ll.insert(6)
ll.insert(3)
ll.insert(1)
ll.printLinkedList()
The way you defined linkedList, it expects an instance of linkListNode as an argument, not a value.
ll = linkedList(linkedListNode("10"))
When you initialize the linkedList object you are passing a string as a parameter:
ll=linkedList("10")
As a result self.head will be equal to string "10"

Python Linkledlist addNode() not correct

I'm writing a simple linked list implementation and am struggling to understand why my code doesn't work. I have a ListNode class and a LinkedList node which contains the head and tail nodes of the list. The addNode() function simply creates a new ListNode, change the self.tail.next = newNode, then set the tail to be the newNode.
When I try to run the following code, I would get the error "AttributeError: 'int' object has no attribute 'next'".
l1 = LinkedList(1)
l1.addNode(2)
l1.addNode(4)
Thank you for the help!
Here is my code
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class LinkedList:
def __init__(self, head=ListNode()):
self.head = head
self.tail = head
def addNode(self, val=0):
newNode = ListNode(val)
self.tail.next = newNode
self.tail = newNode
On the first line of your code, you're passing the value 1 to LinkedList, which is an integer, not an instance of ListNode.
So, you should write l1 = LinkedList(ListNode(1)).

how is the object using a variable which is not inside the class or defined anywhere

In this code the object of class Node is using a variable next which is not defined anywhere and the code is still working HOW?How is the object using a variable which is not defined in its class
class Node:
def __init__(self, data):
self.data = data
class LinkedList:
# Function to initialize head
def __init__(self):
self.head = None
# Function to reverse the linked list
def reverse(self):
prev = None
current = self.head
while(current is not None):
next = current.next
current.next = prev
prev = current
current = next
self.head = prev
# Function to insert a new node at the beginning
def push(self, new_data):
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
# Utility function to print the linked LinkedList
def printList(self):
temp = self.head
while(temp):
print(temp.data)
temp = temp.next
llist = LinkedList()
llist.push(20)
llist.push(4)
llist.push(15)
llist.push(85)
print( "Given Linked List")
llist.printList()
llist.reverse()
print ("\nReversed Linked List")
llist.printList()
While in most strongly typed languages this is not possible, Python allows instance attributes to be defined even after the instance has been created and the constructor has run. As long as code does not reference an attribute before it has been defined, there is no issue. See also: Can I declare Python class fields outside the constructor method?
In this particular case the following code would produce an error:
node = Node(42)
if node.next: # Attribute error
print("42 is not the last node")
else:
print("42 is the last node")
However, the only place where new node instances are created is in the push method of the LinkedList class:
def push(self, new_data):
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
As you can see, the next attribute is defined immediately after the node is constructed. So in practice, every node in a linked list will have a next attribute.
Best Practice?
It is open for debate whether this coding practice is advisable. For instance, Pylint has a rule defining-attr-methods which by default will raise a warning when attributes are defined outside of __init__, __new__, setUp, or __post_init__.
Alternative
In this scenario I would certainly prefer to define the next attribute in the constructor, and give the constructor an extra, optional parameter with which next can be initialised:
class Node:
def __init__(self, data, nxt=None):
self.data = data
self.next = nxt
With this change, the push method of the LinkedList class can be reduce to just:
class LinkedList:
# ...
def push(self, new_data):
self.head = Node(new_data, self.head)
That looks a lot more elegant.
Unrelated, but I would also let the constructor of LinkedList accept any number of values to initialise the list with:
class LinkedList:
def __init__(self, *values):
self.head = None
for value in reversed(values):
self.push(value)
Now the main code could create a list with 4 values in one go:
llist = LinkedList(85, 15, 4, 20)

Printing a parse tree :AttributeError: 'NoneType' object has no attribute 'data'

The class should generate a parse tree based on a postfix string, and then call a print function recursively on the root node that will print the parse tree, yet i keep getting the following error: line 15, in infixPrintNode
self.right.infixPrintNode()
AttributeError: 'NoneType' object has no attribute 'infixPrintNode'
I am new to python and i believe the error is instance-related and i am really confused, would appreciate some clarification
import operator
class Node:
def __init__(self, data, left=None, right=None):
self.data, self.left, self.right = data, left, right
def __str__(self):
return self.data
def infixPrintNode(self):
if self:
if self.right:
return self.right.infixPrintNode()
print(self.data)
if self.left:
return self.left.infixPrintNode()
class ParseTree:
def __init__(self, root = None):
self.root = (root)
def __str__(self):
pass # to be implemented
def fromPostfix(self, expression=""):
s=[] #maintain parents
for c in expression.split():
if c in ["+", "-", "*", "/", "^", "#"]:
n=Node(c)
n.right = s.pop()
n.left=s.pop()
s.append(n)
elif c.isnumeric() or c.isalpha() :
n=Node(c)
s.append(n)
else:
raise ValueError("Invalid token! ")
self.root = (s.pop())
print(self.root.left.data)
print(self.root.data)
print(self.root.right.data)
return self.root #or Node(s.pop())
def printinfix(self):
if self.root:
self.root.infixPrintNode()
t=ParseTree("x y +")
t.fromPostfix("x y +")
t.printinfix()
here it is:
def __init__(self, data, left=None, right=None):
you only passed data, so left and right are still None.
n=Node(c)
so you get the:
'NoneType' object has no attribute 'infixPrintNode'

python int object is not callable?

Relatively new to Python.
I'm trying to practice linked list but I'm stuck with an error and couldn't figure out what the issue is.
The error:
self.assertEqual(l.size(), 1)
TypeError: 'int' object is not callable
The code:
from node import Node
class List:
def __init__(self):
self.head = None
self.size = 0
def add(self, item):
temp = Node(item)
temp.setNext(self.head) # ERROR ON THIS LINE
self.head = temp
size += 1
def size(self):
return self.size
...
Node:
class Node:
def __init__(self, data):
self.data = data
self.next = None
....
Test:
import unittest
import unorderedlist
class TestUnorderedList(unittest.TestCase):
def test_add(self):
l = unorderedlist.List()
l.add(8)
self.assertEqual(l.size(), 1)
if __name__ == '__main__':
unittest.main()
It's funny because if I rename the size() to len and call it like l.len() it works fine. Anyone have a clue?
With the line self.size = 0 you hide the methode size, so size is an int and not a method anymore.
You have hidden your method with the attribute.
In your code you are then accessing the attribute which is of type int and so not callable.
Avoid to name methods and attributes the same.
In case you want to achieve properties. There is the #property decorator:
#property
def size(self):
return self._size
In your constructor you just define self._size and work internally with it.

Categories