Python中被多个函数改变的全局变量



我想在类方法中创建一个全局变量,然后通过其他函数更改它。这是我的代码:

def funcA():
global x
print(x)
x = 2
a = funcB()
return x

def funcB():
global x
print(x)
x = 4
return 2


class A():
def method():
x = 0
return funcA()
A.method()

所以我在类方法中创建了变量x,然后在使用这个变量的所有其他方法中我写了global x。不幸的是,它不起作用。我应该改变什么?funcA应打印0,funcB应打印2,最终结果应为4。

一般来说,使用全局变量是不被允许的。如果您看到一组方法都需要操作同一个变量,这通常表明您实际上需要一个类。您在正确的轨道上尝试定义类,但不幸的是语法有点复杂

这里有一个建议:

class A:

def method(self):
self.x = 0  # note use of self, to refer to the class instance
return self.funcA()
def funcA(self):
print(self.x)
self.x = 2
self.funcB()

def funcB(self):
print(self.x)
self.x = 4

a = A() # making an instance of A
a.method() # calling the method on the instance
print(a.x) # showing that x has become 4

全局创建变量。只需在代码开头添加x = 0,就可以了

x = 0
def funcA():
global x
print(x)
x = 2
a = funcB()
return x
def funcB():
global x
print(x)
x = 4
return 2
class A():
def method():
return funcA()
print(A.method())

它现在应该工作了,问题是你在类A中声明了x,所以它不是全局的。

最新更新