下面是我的模块的完整代码,名为util.py
import my_other_module
__IMPORTANT_OBJECT__ = None
def getImportantObject():
if __IMPORTANT_OBJECT__ is None:
__IMPORTANT_OBJECT__ = my_other_module.ImportantObject()
return __IMPORTANT_OBJECT__我的理解是,以双下划线为前缀的变量被视为模块的私有变量。这里的想法是,我想存储一个对重要对象的私有引用,并通过getImportantObject()方法将它返回给任何需要它的人。但是,我不希望在第一次调用该方法之前启动该对象。
然而,当我运行我的代码时,我会得到以下错误:
File "/Users/Jon/dev/util.py", line 6, in getImportantObject
if __IMPORTANT_OBJECT__ is None:
UnboundLocalError: local variable '__IMPORTANT_OBJECT__' referenced before assignment有什么推荐的方法来完成我在这里想要做的事情?
发布于 2012-12-11 17:15:07
变量不被视为私有变量,而是被视为局部变量。
使用global关键字将其标记为:
def getImportantObject():
global __IMPORTANT_OBJECT__
if __IMPORTANT_OBJECT__ is None:
__IMPORTANT_OBJECT__ = my_other_module.ImportantObject()
return __IMPORTANT_OBJECT__https://stackoverflow.com/questions/13825122
复制相似问题