I am new to classes in Python. I was trying to write a linked-list program where I needed a global variable to do the counting of number of nodes instead of a function. So, when I did as follows:
class DoublyLinkedList:
def __init__(self):
self.head = None
self.tail = None
self.count = 0
Then outside the linked list class I was unable to access this self.count (in the part where I created the object of this class etc.) I thought that since it is a local variable to this class I was getting the error. So, I tried this:
count = 0
class DoublyLinkedList:
def __init__(self):
self.head = None
self.tail = None
global count
self.count=0
I was thinking that if I made the global variable a datafield of this class, then I don't need to write:
global count
in every function under this class. But outside the class whenever I am accessing count, it's value is zero. Can someone please help.
Edit: The display function doesn't need this count so I can see my list being created perfectly. I just want to access the number of nodes using count outside the class so that I can check for position validity before calling insert or delete functions, etc. I am attaching the snippet where it is giving me error, if it helps:
pos = int(input("Enter the position : \n"))
if (pos>(count+1))or(pos<1):
print("Invalid Position")