Reputation: 3860
code:
class Example:
pos_list=[]
last_cell=0
def setText(self):
last_cell = 10
pos_list.append(int(10)) #Line 1
print pos_list , last_cell #Line 2
Error: global name 'pos_list' is not defined.
if i access pos_list in Line 1 and Line 2 as
self.pos_List or Example.pos_list
then no error [ which is fine as i'm accessing it as a instance(self) or class(Example) variable ]
but what about last_cell ? i am accessing it without either self or class reference. But in case of pos_list python interpreter was forcing me to use either those two references.
why am able to access last_cell without any reference ?
Upvotes: 0
Views: 62
Reputation:
You aren't. You're just creating a local variable that happens to have the same name.
class Example:
x = 1
def f(self):
x = 2
Example().f()
print(Example.x) #=> 1
Upvotes: 4
Reputation: 58962
Because you declare last_cell as a local variable. When doing pos_list.append()
you are trying to call a method on something that is undefined, which generates an error.
Upvotes: 0