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
.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With