インスタンスを丸ごと保存したく,pickleを利用したのだが,配列のメンバ変数(コードにおける__hoge)が適切に保存できていなかった。sample1.pyではうまく行かず,sample2.pyではうまくいっています。理由はよくわからないが,appendと代入は違うようです。
詳細知っている方は,ぜひコメント頂けたらと思います。
sample1.py
# -*- coding: utf-8 -*-
import os
import pickle
class Test():
__hoge = []
__foo = ""
def __init__(self):
self.__hoge.append("hoge1")
self.__hoge.append("hoge2")
self.__hoge.append("hoge3")
self.__foo = "foo"
return
def print(self):
print(self.__hoge)
print(self.__foo)
return
if __name__ == '__main__':
pickle_path = 'dataset.pkl'
if not os.path.exists(pickle_path):
# initialize class and save pickle
test = Test()
with open(pickle_path, 'wb') as output:
pickle.dump(test, output)
test.print()
# console:
# ['hoge1', 'hoge2', 'hoge3']
# foo
else:
# load pickle
with open(pickle_path, 'rb') as output:
test = pickle.load(output)
test.print()
# console:
# [] <---- why?
# foo
sample2.py
# -*- coding: utf-8 -*-
import os
import pickle
class Test():
__foo = ""
__hoge = []
def __init__(self):
hoge = []
hoge.append("hoge1")
hoge.append("hoge2")
hoge.append("hoge3")
self.__hoge = hoge
self.__foo = "foo"
return
def print(self):
print(self.__hoge)
print(self.__foo)
return
if __name__ == '__main__':
pickle_path = 'dataset.pkl'
if not os.path.exists(pickle_path):
# initialize class and save pickle
test = Test()
with open(pickle_path, 'wb') as output:
pickle.dump(test, output)
test.print()
# console:
# ['hoge1', 'hoge2', 'hoge3']
# foo
else:
# load pickle
with open(pickle_path, 'rb') as output:
test = pickle.load(output)
test.print()
# console:
# ['hoge1', 'hoge2', 'hoge3'] <---- great!
# foo