[PYTHON] Trouble when pickling an instance

I wanted to save the entire instance, so I used pickle, but the member variables of the array (__hoge in the code) could not be saved properly. It doesn't work with sample1.py and it works with sample2.py. I'm not sure why, but append and assignment seem to be different.

If you know the details, please comment.

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

Recommended Posts

Trouble when pickling an instance
What is an instance variable?