我正在尝试在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
这里发生了什么,不应该静态分配实例Null?什么是正确的方法呢?
答案 0 :(得分: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"