从导入模块中的函数访问全局变量 [英] Access global variables from a function in an imported module

查看:372
本文介绍了从导入模块中的函数访问全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数,我从模块中调用。在函数中,我试图访问的两个变量是全局的。当我单独运行IDLE模块时,我仍然可以在函数结束后访问变量,如预期的那样。当我将代码中的函数调用到模块中时,我无法访问变量。

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? "))

运行时的输出本身。

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

并在代码中导入它。

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
>>> 

如何在代码中导入模块或访问'name '或'age'变量。

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.

推荐答案

简单的答案是不要。 Python的全局变量只是模块级的全局变量,甚至模块级的全局变量(即可变模块级全局变量)应该尽可能地避免,并且真正有很少的理由使用它。

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

这篇关于从导入模块中的函数访问全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆