开发者

Why does pickle not see the class 'painter' when loading?

I am working with a o.o.p and trying to use pickle to load a list of lines I save in a .txt file. I can save the data with pickle, but I am not sure why it can't see 'painter' after I have initialized it.

class LoadButton(MTButton):
    def __init__(self, **kwargs):
        supe开发者_C百科r(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

Any help would be awesome. Thanks.


It is because painter = newpainter creates a local variable painter, even if after the part when you call the global painter.
Do something like this:

painter_ = newpainter
scatter.add_widget(painter_)

EDIT: But why don't you use only painter?

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

EDIT 2: Example:

>>> 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
>>> 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜