Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static variables in another file in Python

Tags:

python

I'm currently having trouble modifying a static variable in another file in Python.

FileA

class MainClass(object):
    global_var = 0
    def __init__(self):
        MainClass.global_var = 1

class SecondClass(object):
    def __init__(self):
        MainClass.global_var = 2

if __name__ == '__main__':
    main = MainClass()
    print "After MainClass:" + str(MainClass.global_var)

    second = SecondClass()
    print "After SecondClass:" + str(MainClass.global_var)

    from FileB import ThirdClass
    third = ThirdClass()
    print "After ThirdClass:" + str(MainClass.global_var)

FileB

class ThirdClass(object):
    def __init__(self):
        from FileA import MainClass
        MainClass.global_var = 3

Output

After MainClass:1
After SecondClass:2
After ThirdClass:2

I would like to modify the static variable in MainClass to 3 in FileB. What am I doing wrong? Thanks!

like image 780
WLin Avatar asked Oct 27 '25 13:10

WLin


1 Answers

You've got two separate instances of the MainClass class! This is due to the way Python imports work.

You can verify this by printing id(MainClass) from FileA and also after you've imported it in the __init__ in FileB

This isn't a bug in Python, you're just trying to do something that the Python language does not specify should work.

Experimenting with code like this is good for learning, but I hope you're not trying to do something like this is a real program. There is certainly a better way than spaghetti code like this.

† Apologies to any spaghetti that was offended by this comment.

like image 192
John La Rooy Avatar answered Oct 30 '25 05:10

John La Rooy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!