我有一个案例:
x = "me"
class Test():
global x
def hello(self):
if x == "me":
x = "Hei..!"
return "success"
我用外壳尝试这种情况。
我怎么能print x
的输出/值x
是Hei..!
?
我尝试过
Test().hello # for running def hello
print x # for print the value of x
打印后x
,输出仍然是me
。
您需要global x
在函数内使用而不是类:
class Test():
def hello(self):
global x
if x == "me":
x = "Hei..!"
return "success"
Test().hello() #Use Parenthesis to call the function.
不知道为什么要从类方法更新全局变量,但是另一种方法是将其定义x
为类属性:
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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句