【发布时间】:2012-05-13 09:52:47
【问题描述】:
我试图做这样的事情:
module.py
def __getitem__(item):
return str(item) + 'Python'
test.py
import module
print module['Monty']
我希望打印“MontyPython”。但是,这不起作用:
TypeError: 'module' object is not subscriptable
是否可以在纯 Python 中创建可下标的模块(即不修改其源代码、猴子补丁等)?
【问题讨论】:
-
我正在编写一个需要从各个地方访问某个全局状态的应用程序。我认为有这样的东西会很酷:
import state; state[something_specific] = new_stuff而不是from state_class import state; ... -
我认为这种酷炫不值得付出努力。继续使用 dot 语法。在我看来,它要好得多。