Search code examples
pythonglobal-variablesscopepython-2.6

Accessing a Global Variable in an External Class


I've been learning Python for about a week or so and after my code getting quite large and a bit messy I decided to break it out into separate class files etc. etc. but I've come across a bit of a problem.

I've tried Googling and searching here on SO but I couldn't find my specific problem so forgive me if it has been asked before.

Consider 2 files. test.py and testClass.py I have a global variable in test.py which will also be SET in test.py but I want to access that variable in a function in testClass.py. Here's some code to help explain.

test.py would look like this:

import testClass

dict = {}
z = 5

dict['test'] = testClass.testClass(1, 3)

print dict['test'].sum()

testClass.py would look like this:

class testClass:
    def __init__(self, x, y):
        self.foo = x
        self.bar = y

    def sum(self):
        global z
        return self.foo + self.bar + z

Currently the interpreter is spitting out:

NameError: global name 'z' is not defined

After re-reading the Python references for classes and variable scope I thought I had it nailed but obviously not.

The outcome of this all is simply to be able to iter through a dictionary of object instances and run a sequence of various check functions etc contained within the external class.


Solution

  • Global is global to the file (module) so you might want to include it in a class.