I am trying to access a global variable which was defined in my main Python file from inside an object instance. I have read some other questions on the topic and I learned I need to use the global keyword inside my class method first.
However, even so, my code does not seem to work:
from secondclass import SecondClass
somelist = [1,2,3]
obj = SecondClass()
obj.mainmethod()
And here is my other file containing secondclass:
class SecondClass():
def mainmethod(self):
global somelist
print (somelist)
Even through I am using the global keyword, Python still gives me error:
NameError: name 'somelist' is not defined
Why is that?
globalis local to the module. It is not global worldwide. If your class needs that list, then you should pass it to the constructor.