本文介绍了Python:给模块下标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图做这样的事情:

module.py

def __getitem__(item):
    return str(item) + 'Python'

test.py

import module
print module['Monty']

我希望打印MontyPython".但是,这不起作用:

I expected "MontyPython" to be printed. However, this doesn't work:

TypeError: 'module' object is not subscriptable

是否可以在纯 Python 中创建可下标的模块(即无需修改其源代码、猴子补丁等)?

Is it possible to create a subscriptable module in pure Python (i.e. without modifying its source code, monkey-patching, etc.)?

推荐答案

>>> class ModModule(object):
    def __init__(self, globals):
        self.__dict__ = globals
        import sys
        sys.modules[self.__name__] = self
    def __getitem__(self, name):
        return self.__dict__[name]


>>> m = ModModule({'__name__':'Mod', 'a':3})
>>> import Mod
>>> Mod['a']
3

# subclassing the actual type won't work
>>> class ModModule(types.ModuleType):
    def __init__(self, globals):
        self.__dict__ = globals
        import sys
        sys.modules[self.__name__] = self
    def __getitem__(self, name):
        return self.__dict__[name]


>>> m = ModModule({'__name__':'Mod', 'a':3})

Traceback (most recent call last):
  File "<pyshell#114>", line 1, in <module>
    m = ModModule({'__name__':'Mod', 'a':3})
  File "<pyshell#113>", line 3, in __init__
    self.__dict__ = globals
TypeError: readonly attribute

您可以使用 ModModule(globals()) 来替换 sys 中的当前模块.

you may use ModModule(globals()) to replace the current module in sys.

这篇关于Python:给模块下标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 08:13