xh c
xh c

Reputation: 15

Python How can I use global variables in a class

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'

Upvotes: 0

Views: 175

Answers (2)

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()

Upvotes: 3

Carlos
Carlos

Reputation: 113

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

Upvotes: -1

Related Questions