Python How can I use global variables in a class

Viewed 48

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 Answers

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()
class TestGlobal():
    def one(self):
        global a
        a = "i m a"
    def two(self):
        global a
        print(a)

or you can write this way

class TestGlobal():
    global a
    def __init__(self):
        self.a = self.one()
    
    def one(self):
        self.a = "i m a 5"

    def two(self):
        print('------------------>',self.a)

when you defining any variable in class and method then it consider for particular class or method. So if it is global variable then call it as global first then used it.

"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)
Related