4

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.

1 Answer 1

4

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

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.