Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading