Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access global variable in Python?

I have a case :

x = "me"

class Test():    
    global x

    def hello(self):
        if x == "me":
            x = "Hei..!"
            return "success"

I try this case with shell.

How I can print x which the output/value of x is Hei..!?

I tried with

Test().hello # for running def hello
print x # for print the value of x

After I print x, the output is still me.

like image 965
bennysantoso Avatar asked Oct 18 '25 10:10

bennysantoso


1 Answers

You need to use global x inside the function not class:

class Test():
    def hello(self):
        global x
        if x == "me":
            x = "Hei..!"
            return "success"

Test().hello() #Use Parenthesis to call the function.

Don't know why you want to update a global variable from class method, but one another way will be to define x as a class attribute:

class Test(object): #Inherit from `object` to make it a new-style class(Python 2)
    x = "me"
    def hello(self):
        if self.x == "me":
            type(self).x = "Hei..!"
            return "success"

Test().hello()
print Test.x
like image 127
Ashwini Chaudhary Avatar answered Oct 20 '25 23:10

Ashwini Chaudhary



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!