作者:
ResolaQQ (ResolaQQ)
2016-02-03 20:38:17constants
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__?
英文太爛,實在抱歉