Python 类型错误:“模块”对象不可下标

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43147823/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 22:34:49  来源:igfitidea点击:

TypeError: 'module' object is not subscriptable

python

提问by DammondCircuit

mystuff.py includes a module. I'm using python version 3.6.

mystuff.py 包含一个模块。我正在使用 python 3.6 版。

mystuff = {'donut': "SHE LOVES DONUTS!"}

mystuffTest.py includes this

mystuffTest.py 包括这个

import mystuff

print (mystuff['donut'])

The error that I receive when I run mystuffTest.py as follows:

我在运行 mystuffTest.py 时收到的错误如下:

$ python3.6 mystuffTrythis.py 
Traceback (most recent call last):
  File "mystuffTrythis.py", line 3, in <module>
    print (mystuff['donut'])
TypeError: 'module' object is not subscriptable

So far I haven't seen this exact error here on stackoverflow. Can anyone explain why I am getting this error?

到目前为止,我还没有在 stackoverflow 上看到这个确切的错误。谁能解释为什么我收到这个错误?

回答by Aaron N. Brock

import mystuffis importing the module mystuff, not the variable mystuff. To access the variable you'd need to use:

import mystuff正在导入模块mystuff,而不是变量mystuff。要访问您需要使用的变量:

import mystuff
print(mystuff.mystuff['donut'])

EDIT:It's also possible to import the variable directly, using:

编辑:也可以直接导入变量,使用:

from mystuff import mystuff
print(mystuff['donut'])