>>> 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中的當前模塊。
你爲什麼要這樣做? – cobie
我正在編寫一個應用程序,需要從各個地方訪問特定的全局狀態。我認爲這樣做會很酷: 'import state; state [something_specific] = new_stuff' than 'from state_class import state; ...' – Pastafarianist
我不認爲這種冷靜是值得的。只要繼續* dot *語法即可。在我看來,它更好。 – cobie