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

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

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

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 (or as your example seems to use, folder.test_list).

from folder import test_function
folder.test_list = []
object = test_function()
object.loop_unit('teststr')
print(folder.test_list)
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