constants
all module globals are considered constants. Their binding must not be changed
at run-time. Moreover, global (i.e. prebuilt) lists and dictionaries are
supposed to be immutable: modifying e.g. a global list will give inconsistent
results. However, global instances don't have this restriction, so if you need
mutable global state, store it in the attributes of some prebuilt singleton
instance.
按照上面的说法,我本来以为可以这样用
class Global_State:
def __init__(self):
initialize_other_library()
self.global_mutable_variable = 0xFF
global_state = Global_State()
但是实际上的结果很谜,大概是
1. initialize_other_library 这个函式根本没有被呼叫
2. global_mutable_variable 可以使用,而且其值确实一开始为 0xFF
3. 有时候程式会当掉
据推测,我怀疑 __init__ 根本没有被呼叫,如果在 main 里面呼叫 __init__ 的话
1. initialize_other_library 确实有被呼叫
2. global_mutable_variable 可以使用,而且其值确实一开始为 0xFF
3. 程式不会当掉
想请问,按照那段英文,到底允不允许这样产生一个 module global instance 供使用?
如果允许,为什么我要自己呼叫 __init__?
英文太烂,实在抱歉