为什么pickle在装载时看不到班级的“画家”?

时间:2011-06-07 16:58:46

标签: python pickle

我正在使用o.o.p并尝试使用pickle加载我保存在.txt文件中的行列表。我可以用pickle保存数据,但我不确定为什么在我初始化之后它看不到'painter'。

class LoadButton(MTButton):
    def __init__(self, **kwargs):
        super(LoadButton, self).__init__(**kwargs)
        self.buttonLoad = kwargs.get('painter')
    def on_release(self, touch):
        if touch.device != 'wm_pen':
            newLoad = self.buttonLoad
            loadFile = open('savefiles/savetest.txt', 'rb')
            newpainter = painter
            scatter.remove_widget(painter) # if removed error: EOF, no data read
            # error: local var 'painter' referenced before assignment
            oldlines = pickle.load(loadFile)
            painter = newpainter
            scatter.add_widget(painter)
            pprint.pprint(oldlines)
            loadFile.close()
            return True

任何帮助都会很棒。感谢。

1 个答案:

答案 0 :(得分:1)

这是因为painter = newpainter创建了一个本地变量painter,即使在您调用全局painter之后的部分之后也是如此。 做这样的事情:

painter_ = newpainter
scatter.add_widget(painter_)

编辑:但为什么不只使用painter

        scatter.remove_widget(painter)
        oldlines = pickle.load(loadFile)
        scatter.add_widget(painter)

编辑2: 例如:

>>> bar = 'Bar'
>>> def foo():
...     bar  # This is the local bar. It has not been assigned a value yet.
...     bar = 'Local Bar'  # Here I assign a value to the bar.
... 
>>> foo()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in foo
UnboundLocalError: local variable 'bar' referenced before assignment
>>>