作者stupidgod08 (笨神)
看板Python
标题Re: [问题] 英文实在看不懂,能不能请各位帮忙解释?
时间Thu Feb 4 02:23:40 2016
如果你的程式码是照下面写的
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__?
: 英文太烂,实在抱歉
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 115.43.25.98
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/Python/M.1454523824.A.936.html
1F:→ stupidgod08: initial_other...如果是一次性的就放入if里吧 02/04 02:48
2F:推 ResolaQQ: 我在写RPython,很多语法不能用,像您这个就不行 02/04 04:30
3F:→ ResolaQQ: 目前已经移除所有全域变数,如果再出问题会再来版上询问 02/04 04:32