import json class Person: def __init__(self, name, age): self.name = name self.age = age def to_json(self): return {'name': self.name, 'age': self.age} def encode_person(obj): if isinstance(obj, Person): return obj.to_json() return obj person = Person('Alice', 25) json_str = json.dumps(person, default=encode_person) print(json_str)In this example, we define a custom serialization function called `encode_person` that checks if the object being serialized is an instance of the `Person` class. If it is, it calls the `to_json` method of the `Person` instance to get a JSON-compatible dictionary representation of the object. We then pass `encode_person` as the `default` argument to `json.dumps` to tell it to use our custom serialization function. This code requires the built-in json package in Python.