如何在Python中访问全局变量?

4 投票
1 回答
3054 浏览
提问于 2025-04-18 00:47

我有一个情况:

x = "me"

class Test():    
    global x

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

我用命令行尝试了这个情况。

我该怎么做才能让 print x 的输出/值变成 Hei..! 呢?

我试过:

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

但是当我打印 x 的时候,输出仍然是 me

1 个回答

4

你需要在函数里面使用 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

撰写回答