1

I need to access global variable (g). which was present in another python file inside the class. Please suggest me how to access.

test1.py:

class cls():
    def m1(self):
       inVar = 'inside_method'
       global g
       g = "Global"
       x = 10
       y = 20
       print("Inside_method", inVar)
       print (x)
       print (y)
       print (g)
obj = cls()
obj.m1()

test2.py:

from test1 import *
print (cls.m1) # I can access all variables in method
print (cls.m1.g) # getting error while accessing variable inside the function

I expected to access variable 'g' from my test2.py. Could you please help me out.

1
  • g simply does not belong to m1. Commented May 21, 2019 at 10:35

1 Answer 1

2

Globals are attributes of the module, not the c1 class or m1 method. So if you imported the module instead of all the names from the module, you could access it there:

import test1

# references the `m1` attribute of the `cls` name in he `test1` module
# global namespace.
print(test1.cls.m1)
# references the `g` name in he `test1` module global namespace.
print(test1.g)

You also run the cls().m1() expression at the top level in the test1 module, so it is executed the first time anything imports test1. This means that your from test1 import * expression created a name g in your test2 namespace too:

from test1 import *  # imported cls, obj and g

print(g)  # "Global"

However, that reference will not change along with any assignments to the test1.g global.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.