python中的未绑定变量

2024-09-30 00:38:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用python制作一个玩具singleton来学习该语言的来龙去脉,但遇到了python如何工作的问题。我这样宣布班级

class ErrorLogger:
  # Singleton that provides logging to a file  
  instance = None

  def getInstance():
    # Our singleton "constructor"
    if instance is None :
      print "foo"

当我叫它

^{pr2}$

我明白了

 File "/home/paul/projects/peachpit/src/ErrorLogger.py", line 7, in getInstance
    if instance is None :
 UnboundLocalError: local variable 'instance' referenced before assignment

这是怎么回事,实例不应该被静态地赋值为Null吗?正确的方法是什么?在


Tags: instancenone语言ifthatisprovidesclass
1条回答
网友
1楼 · 发布于 2024-09-30 00:38:19

您必须使用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"

相关问题 更多 >

    热门问题