Global variable in Python changed by multiple functions

I want to create a global variable inside a class method and then change it by other functions. This is my code:

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()

So I create variable x inside class method and then in all other methods which uses this variable I wrote global x. Unfortunately it doesn’t work. What should I change? funcA should print 0, funcB should print 2 and the final results should be 4.

>Solution :

In general, use of global variables is frowned upon. If you see that a group of methods all need to manipulate the same variable it is often a sign that you actually want a class. You are on the right track trying to define the class, but unfortunately the syntax is a little more complicated

Here is one suggestion:

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

Leave a Reply