Home > Software engineering >  Global variable in Python changed by multiple functions
Global variable in Python changed by multiple functions

Time:06-24

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.

CodePudding user response:

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

CodePudding user response:

create the variable globally. just add x = 0 at the starting of your code, it will work

CodePudding user response:

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

It should work now, the problem was that you declared x inside class A, so it wasn't global.

  • Related