2024-05-29 08:09:30 发布
网友
我试着做这样的事情:
模块.py
def __getitem__(item): return str(item) + 'Python'
测试.py
我本以为《蒙提ython》会印出来。但是,这不起作用:
TypeError: 'module' object is not subscriptable
是否可以用纯Python创建一个可订阅的模块(即不修改其源代码、monkey补丁等)?在
>>> 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中的当前模块。在
您可以使用ModModule(globals())替换sys中的当前模块。在
相关问题 更多 >
编程相关推荐