Skip to content

Instantly share code, notes, and snippets.

@masaki925
Last active May 13, 2017 02:34
Show Gist options
  • Save masaki925/234c4d88228f987bee47bd47e2749fcb to your computer and use it in GitHub Desktop.
Save masaki925/234c4d88228f987bee47bd47e2749fcb to your computer and use it in GitHub Desktop.
pystudy_class_in_pickle

あるクラスのインスタンスを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'>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment