如何在python中的其他模块中使用变量?

时间:2012-01-13 19:47:58

标签: python

那是one.py:

test = {'1': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25]}
import two
two.example()

那是两个.py:

def example():
    print test[1][5]

你能告诉我为什么会因以下错误而失败吗?

NameError: global name 'test' is not defined

谢谢!

5 个答案:

答案 0 :(得分:1)

因为你的two.py不知道test是什么,所以你应该将其作为参数传递给example

one.py:

test = {1: [1, 2, 3, 4, 5, 6]}
import two
two.example(test)

two.py:

def example(test):
    print test[1][5]

注意:我冒昧地将test dict条目从'1'更改为1,因为您拨打了test[1][5]而不是{{} 1}}。

答案 1 :(得分:1)

在Python中,一切都是对象。 甚至模块

testone模块对象的属性,而不是two模块对象的属性。因此,在two的代码中,它不在范围内。

答案 2 :(得分:0)

每个模块(包括脚本文本)都有自己的全局变量名称空间(global symbol table)。可以访问其他模块的变量,但不是那么容易。此外,通常更好的方法是将它们作为函数参数传递。

答案 3 :(得分:0)

您需要在two.py文件中导入one.py,以使其位于命名空间中。

Two.py:

from one import *
print test

答案 4 :(得分:-1)

您可以在功能

中导入它
def example():
    from one import test
    print test[1][5]

或者您可以将测试作为变量传递

#one.py
two.example(test)

#two.py
def example(test):
    print test[1][5]
相关问题