Python: Prepare a serializer for the class instance:

# jose.py

class BaseObjectSerializer(json.JSONEncoder):

    def default(self, obj):
        if isinstance(obj, Enum):
            return obj.value

#: ...... Other object judgment

        if isinstance(obj, object):

#: Dict the field #: Ignore fields starting with an underscore return dict([(k, v) for k, v in obj.dict.items() if not k.startswith('_')])

        return super(BaseObjectSerializer, self).default(obj)

Specify the encoder class with the to_json () method and do json.dumps:

# jose.py 

class BaseObject(object):
    _serializer = BaseObjectSerializer    

    def to_json(self, *args, **kwargs):
        kwargs['cls'] = self._serializer    #: Custom Serializer
        return json.dumps(self, *args, **kwargs)

Only the result of addition is serialized, and holders in the middle are not serialized. ::

from jose import BaseObject


class Message(BaseObject):

    def __init__(self, *args, **kwargs):
        super(Message, self).__init__(*args, **kwargs)
        self.total = 0 
        self._x =0
        self._y =0

    def sum(self, x, y): 
        self._x = x 
        self._y = y 
        self.total = self._x + self._y


m = Message()
m.sum(3, 4)
assert m.total == 7
assert m.to_json() == '{"total": 7}'
assert m._x == 3

m2 = Message()
assert m2._x == 0

Recommended Posts

Python: Prepare a serializer for the class instance:
[Python] class, instance
Python class, instance
Created a Python wrapper for the Qiita API
Hit a method of a class instance with the Python Bottle Web API
A python implementation of the Bayesian linear regression class
Python: Class and instance variables
Python class variables and instance variables
Don't take an instance of a Python exception class directly as an argument to the exception class!
How to use the __call__ method in a Python class
Try a similar search for Image Search using the Python SDK [Search]
[Python] Building a virtual python environment for the pyramid tutorial (summary)
Create a Twitter BOT with the GoogleAppEngine SDK for Python
How to write a Python class
Python class definitions and instance handling
"The easiest Python introductory class" modified
[Python] Make the function a lambda function
See python for the first time
Examine the object's class in python
What is the python underscore (_) for?
[Python] Inherit a class with class variables
Prepare the environment for Atom for Pythonista
Command for the current directory Python
A memorandum of understanding for the Python package management tool ez_setup
Create an instance of a predefined class from a string in Python
[Road to Python Intermediate] Call a class instance like a function with __call__
Understanding the python class Struggle (1) Let's move it for the time being
Create a color picker for the color wheel with Python + Qt (PySide)
The story of making a standard driver for db with python.
[Introduction to Python] How to use the in operator in a for statement?
I made a scaffolding tool for the Python web framework Bottle
Prepare a distributed load test environment with the Python load test tool Locust
I thought a Python class variable was an instance variable and died
Generate a first class collection in Python
Introducing the BOT framework Minette for Python
Prepare a Python virtual environment for your project with venv with VS Code
Create a Python function decorator with Class
Build a blockchain with Python ① Create a class
Create a Python development environment locally at the fastest speed (for beginners)
[Python] How to make a class iterable
[Introduction to Udemy Python3 + Application] 47. Process the dictionary with a for statement
Write the test in a python docstring
Find the dates for a jarring tournament
Python Master RTA for the time being
Let's create a virtual environment for Python
Change the list in a for statement
Search the maze with the python A * algorithm
Launch the Discord Python bot for 24 hours.
Make Qt for Python app a desktop app
MongoDB for the first time in Python
[python] Get a list of instance variables
[python] [meta] Is the type of python a type?
Get a token for conoha in python
Pandas of the beginner, by the beginner, for the beginner [Python]
A tool for easily entering Python code
Prepare the development environment for keyhac for Mac
Generate a class from a string in Python
The story of blackjack A processing (python)
[Python] It was very convenient to use a Python class for a ROS program.
Get a datetime instance at any time of the day in Python
A useful note when using Python for the first time in a while