Search code examples
pythonclassimportglobal-variables

Python, define global variable in a class and import this class for main script,but that global variable is not defined


I have a basic.py file under a specific folder which defined a class:

class test_function:
    def loop_unit(self,str):
        global test_list
        test_list.append(str)

I have another main.py which have following code

from folder import basic
test_list=[]
object=basic.test_function()
object.loop_unit('teststr')
print(test_list)

it will give an error says

name 'test_list' is not defined(it trackback to test_list.append(str) ) I actually defined global variable in the function, and I defined it at the start of the main code, why it still said this is not defined?


Solution

  • You defined main.test_list; test_function.loop_unit wants basic.test_list.

    from folder import basic
    basic.test_list = []
    object = basic.test_function()
    object.loop_unit('teststr')
    print(basic.test_list)