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?
CodePudding user response:
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)
CodePudding user response:
Try to do this in your class definition:
class test_function:
def __init__(self):
self.test_list = []
def loop_unit(self,str):
sel.test_list.append(str)
from folder import basic
#test_list=[] --remove this line
object=basic.test_function()
object.loop_unit('teststr')
#print(test_list) ---remove this line but add this:
print(object.test_list)
Try and tell me if it works.