如果你的程式碼是照下面寫的
class Global_State:
def __init__(self):
initialize_other_library()
self.global_mutable_variable = 0xFF
那試試這個單例寫法, 應該能相容
class Global_State:
def __init__(self):
initialize_other_library()
if not hasattr(Global_State, "global_mutable_variable"):
Global_State.global_mutable_variable = 0xFF
其它地方存取時記得用Global_State.global_mutable_variable
用Class去存取, 而不是用Instance存取
再看還會不會當
有打錯字就自行修改一下
※ 引述《ResolaQQ (ResolaQQ)》之銘言:
: 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__?
: 英文太爛,實在抱歉