我正在尝试在python中制作一个玩具单例来学习语言的来龙去脉,并且遇到了python如何工作的问题.我宣布这样的课程
class ErrorLogger:
# Singleton that provides logging to a file
instance = None
def getInstance():
# Our singleton "constructor"
if instance is None :
print "foo"
Run Code Online (Sandbox Code Playgroud)
我打电话的时候
log = ErrorLogger.getInstance()
Run Code Online (Sandbox Code Playgroud)
我明白了
File "/home/paul/projects/peachpit/src/ErrorLogger.py", line 7, in getInstance
if instance is None :
UnboundLocalError: local variable 'instance' referenced before assignment
Run Code Online (Sandbox Code Playgroud)
这里发生了什么,不应该静态分配Null?这样做的正确方法是什么?
你必须用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"
Run Code Online (Sandbox Code Playgroud)