2024-heraklion-scientific-p.../notebooks/02b_Serialization_teacher_edition.ipynb
2024-08-27 15:52:41 +03:00

3.6 KiB

Serialization demo

In [2]:
import json
import numpy as np
import pickle

pickle is simple but can be dangerous

In [3]:
class SomethingSimple:
    def __init__(self, foo, bar):
        self.foo = foo
        self.bar = bar
In [4]:
simple = SomethingSimple(foo=3, bar='two')
In [ ]:

In [ ]:

JSON is still quite simple, and allows you a closer control

In [7]:
class SomethingNice:

    def __init__(self, foo, bar):
        self.foo = foo
        self.bar = bar

    @classmethod
    def from_json(cls, fname):
        pass

    def to_json(self, fname):
        pass
In [8]:
so_nice = SomethingNice(foo=3, bar='two')
so_nice.__dict__
Out[8]:
{'foo': 3, 'bar': 'two'}
In [ ]: