I know that in Python there is no such thing as private variable, that is to say, any variable within a class can be accessed from anywhere. Does this also apply to class methods? If I have a variable within a class method, does it mean its value can also be altered from the outside?
The major problem I'm facing is I have nested loops within class. I have a simple example situation below (code 1). I have a variable i in the main code, and the class method can directly read its value. However, it seems I can't alter i's value from within the class method, which is shown in code 2. So what exactly decides the rule of variable accessibility in python? What should I do to avoid variables being overwritten without me knowing it?
Code 1
class Lol():
j = 3
def test(self):
for j in range(i, 4):
print(i, self.j)
lol = Lol()
for i in range(0, 2):
lol.test()
The output is the following:
0 3
0 3
0 3
0 3
1 3
1 3
1 3
Code 2
class Lol():
j = 3
def test(self):
i = 0
lol = Lol()
for i in range(0, 2):
print(i)
lol.test()
print(i)
Output:
0
0
1
1
This means the class method cannot change the value of the variable i
in the main script.