Access global variables from a function in an imported module

假如想象 提交于 2019-12-22 04:40:50

问题


I have a function that i'm calling from module. Within the function the two variables i'm trying to access are made global. When I run the module in IDLE by itself I can still access the variables after the function ends, as expected. When I call the function in the code that I have imported the module into I can't access the variables.

#module to be imported

def globaltest():
    global name
    global age
    name = str(raw_input("What is your name? "))
    age = int(raw_input("What is your age? "))

The output when I run it by itself.

>>> globaltest()
What is your name? tom
What is your age? 16
>>> name
'tom'
>>> age
16

And the code where import it.

import name_age

name_age.globaltest()

but when I run attempt to access the variables in the code where I have imported it.

What is your name? tom
What is your age? 16
>>> name

Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
 name
NameError: name 'name' is not defined
>>> 

How can I make the variable global in the code where I have imported the module or access the 'name' or 'age' variables in the function.


回答1:


The simple answer is "don't". Python's "globals" are only module-level globals, and even module-level globals (mutable module-level globals that is) should be avoided as much as possible, and there's really very very few reasons to use one.

The right solution is to learn to properly use function params and return values. In your case a first approach would be

#module.py

def noglobaltest():
    name = str(raw_input("What is your name? "))
    age = int(raw_input("What is your age? "))
    return name, age 

and then:

from module import noglobaltest

name, age = noglobaltest()
print "name :", name, "age :", age



回答2:


Just change your import statement to this one:

from name_age import *

example:

In [1]: from name_age import *
In [2]: print name
Out[2]: 'tom'

Otherwise, if you want to use the import name_age statement, then you have to access your global variables through the module name reference, that is:

example:

In [1]: import name_age
In [2]: print name_age.name
Out[2]: 'tom'


来源:https://stackoverflow.com/questions/15924700/access-global-variables-from-a-function-in-an-imported-module

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!