I want to learn basics of classes in Python and got stuck. I declared same name of class variables and instance variable so that I could understand difference better but when I am using class variable inside the class methods it is showing error like NameError: global name 'a' is not defined. Can someone please tell me how to declare class variable inside and outside the class if both class variables and instance variables have same name. Code is given below and so error in output
class abc:
a=10
def __init__(self,a):
self.a=a
def mod1(self):
global a
a=5
self.a=105
def mod2(self):
a=15
self.a=110
def read(self):
print(self.a)
print(a)
b=abc(20)
print(b.a)
b.read()
b.mod1()
b.read()
b.mod2()
b.read()
Error is
20
20
Traceback (most recent call last):
File "/Users/rituagrawal/PycharmProjects/untitled2/code/garbage.py", line 18, in <module>
b.read()
File "/Users/rituagrawal/PycharmProjects/untitled2/code/garbage.py", line 14, in read
print(a)
NameError: global name 'a' is not defined
Process finished with exit code 1