Python中的未绑定变量
我正在尝试在Python中制作一个简单的单例模式,目的是学习这个语言的细节,但遇到了一些问题。我的类是这样声明的:
class ErrorLogger:
# Singleton that provides logging to a file
instance = None
def getInstance():
# Our singleton "constructor"
if instance is None :
print "foo"
当我用下面的方式调用它时:
log = ErrorLogger.getInstance()
我得到了:
File "/home/paul/projects/peachpit/src/ErrorLogger.py", line 7, in getInstance
if instance is None :
UnboundLocalError: local variable 'instance' referenced before assignment
这到底是怎么回事?难道实例不应该静态地被赋值为空吗?那正确的做法是什么呢?
1 个回答
5
你需要用 ErrorLogger
这个前缀来调用它,因为它是一个静态变量。
class ErrorLogger:
# Singleton that provides logging to a file
instance = None
@staticmethod
def getInstance():
# Our singleton "constructor"
if ErrorLogger.instance is None :
print "foo"