所以这是一个非常简单的问题.如何添加__getitem__到Python模块.我大多只是希望它易于使用,但令人困惑的是它为什么不让我"设置它".下面是一个简单的__getitem__半工作示例,但我希望other['test']能够工作.
这是完整的输出:
hello
hello
Traceback (most recent call last):
File "main.py", line 4, in <module>
print other['test']
TypeError: 'module' object has no attribute '__getitem__'
Run Code Online (Sandbox Code Playgroud)
main.py
import other
print other.get('test')
print other.__getitem__('test')
print other['test']
Run Code Online (Sandbox Code Playgroud)
other.py
test = 'hello'
def __getitem__(name):
return globals()[name]
get = __getitem__
Run Code Online (Sandbox Code Playgroud)
我试图设置__getitem__使用globals()藏汉,globals()['__getitem__'] = __getitem__.它没用.我试着把它设置好main.py.所以我很困惑为什么它坚持不允许我使用它other['test'].
如果这是不可能的,那么一个简短的理由就是好的.
在类型上查找特殊方法,而不是在实例上查找.Python寻找type(other).__getitem__()并且不可用.您必须将该__getitem__方法添加到该module类型; 你不能用Python.
你必须用你自己的类的实例替换整个module实例sys.modules来实现你想要的:
class MyModule(object):
def __init__(self, namespace):
self.__dict__.update(namespace)
def __getitem__(name):
return self.__dict__[name]
import other
import sys
sys.modules[other.__name__] = MyModule(other.__dict__)
Run Code Online (Sandbox Code Playgroud)