Python:下标一个模块 [英] Python: subscript a module

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

问题描述

我正在尝试做这样的事情:

I was trying to do something like this:

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:下标一个模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆