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")
CodePudding user response:
there is no need to make a global variable in the class instead you can make a self.[variable name] however for changing the variable value you can self.[var name] = [new value]
for example :
class myclass:
def __init__(self):
self.counter = 1
classvar = myclass();
print(classvar.counter)
CodePudding user response:
I think you misunderstood the meaning of the keyword global. global is used when you want to access / modify a variable which was defined in the normal script, not in the function, e.g.
#test.py
c = 1
def test1():
c = 3 #this will not modify the c which we declared earlier
test1()
print(c) #will print 1
def test2():
global c #this tells the interpreter to look for the previously defined c
c = 3
test2()
print(c) #will print 3
Now to access members of an object, you just need to use objectname.variablename
