あるクラスのインスタンスをpickle 化したとき、pickle を読み込んで利用するときにはクラスを別途import する必要がある、という話
- pickle 作成用スクリプト
import pickle
class Hoge():
def __init__(self, greeting):
self.greeting = greeting
def hello(self):
print(self.greeting)
if __name__ == '__main__':
hoge = Hoge('hi')
hoge.hello()
pickle.dump(hoge, open("save.p", "wb"))
- pickle 利用スクリプト
import pickle
#from learn import Hoge
hoge = pickle.load(open("save.p", "rb"))
hoge.hello()
- Hoge をimport しないとエラー
$ python main.py
Traceback (most recent call last):
File "a.py", line 10, in <module>
hoge = pickle.load(open("save.p", "rb"))
AttributeError: Can't get attribute 'Hoge' on <module '__main__' from 'a.py'>