0

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 ?

2
  • 1
    You're missing a parenthesis on line 1 :) Commented Apr 29, 2013 at 17:47
  • Please do the official Python tutorial - Python's object model is quite different from what you may have learned from more mainstream OOPLs. Commented Apr 29, 2013 at 18:21

2 Answers 2

4

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
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.