Do you guys use SymPy? When I use SymPy with Jupyter Notebook, the output formula is beautifully shaped and displayed. Something like this. Do you know how to create an object that produces such rich output?
It was written in IPython documentation. This can be achieved by implementing a method with a name of the form _repr_ * _
. What applies to this *
is
there is. I think SymPy is probably implemented in LaTeX, but this time let's use SVG, which is easy to understand.
Face() + Eye(35, 40) + Eye(65, 40) + Mouth(50, 75)
The implementation is as follows.
class Component():
def __init__(self, items = None):
self.items = items or [self]
def __add__(self, target):
return Component(self.items + target.items)
def _repr_svg_(self):
return ''.join([
'<svg width="100" height="100">',
*map(str, self.items),
'</svg>'
])
class Face(Component):
def __str__(self):
return '<circle cx="50" cy="50" r="45" fill="none" stroke="black" stroke-width="1" />'
class Eye(Component):
def __init__(self, x, y):
super().__init__()
self.x, self.y = x, y
def __str__(self):
return f'<circle cx="{self.x}" cy="{self.y}" r="5" fill="black" />'
class Mouth(Component):
def __init__(self, x, y):
super().__init__()
self.x, self.y = x, y
def __str__(self):
return f'<path d="M{self.x} {self.y} l15 -5 h-30 Z" fill="none" stroke="black" stroke-width="1" />'
Recommended Posts