0

the code:

class ceshi():
    def one(self):
        global a
        a = "i m a"

    def two(self):
        print(a)


if __name__ == '__main__':
    ceshi().two()

error message: NameError: name 'a' is not defined

Didn't I define "a"? why the error message is 'name "a" is not defind'

3
  • Didn't I define "a" no, you didn't. a = something will be defining a. Since you want it to be global it should be outside the class scope. Commented Sep 15, 2022 at 13:46
  • 2
    you never called one() method so the global variable does not exist. It would exist if you create it outside class first Commented Sep 15, 2022 at 13:49
  • The problem is not that a isn't out of the class. You can perfectly leave it within def one() and be global, but you also need to actually make a call to function one(), which you never do. Commented Sep 15, 2022 at 13:51

2 Answers 2

3

You never actually define a. Just because you have it within function one does not mean that this function will be called.

You should either move a out of the class scope:

 a = "i m a"
 class ceshi():
    def one(self):
        # some other code

    def two(self):
        print(a)

or make a call to one() before calling two(), in order to define a.

if __name__ == '__main__':
    ceshi().one()
    ceshi().two()
Sign up to request clarification or add additional context in comments.

Comments

-1

"a" is only defined inside def one(), so you should declare it outside the method scope and later on define its value inside def one() if that's what you want to do. You could just leave it inside def one() but if the method isn't called, it still won't work.

So your code should look like:

class ceshi():
    global a
    def one(self):       
        a = "i m a"

    def two(self):
        print(a)

5 Comments

Why do you think that global a should be moved out of the method into the class?
I think OP is getting this error because he didn't call the method one() before calling two(), so moving it out of the method would fix it?
The OP not calling one() is the problem. Moving the global statement does not help that. Global statements go in a region of local scope to indicate that a referenced variable is global instead of local.
I see, I thought it would print None if the variable is declared but not defined. Should I delete the answer when it's incorrect?
Whether you delete it is up to you. The correct answer has been provided by another user.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.