Skip to main content
Stack Overflow
  1. About
  2. For Teams

Return to Revisions

1 of 3
Udi
  • 30.8k
  • 9
  • 105
  • 134

Related: While constructing a class, def _reper_html_(self): ... can be used to create a custom HTML representation of its instances:

class Foo:
 def _repr_html_(self):
 return "Hello <b>World</b>!"
o = Foo()
o

will render as:

Hello World!

An advanced example:

from html import escape # Python 3 only :-)

class Todo:
 def __init__(self):
 self.items = []
 
 def add(self, text, completed):
 self.items.append({'text': text, 'completed': completed})
 
 def _repr_html_(self):
 return "<ol>{}</ol>".format("".join("<li>{} {}</li>".format(
 "☑" if item['completed'] else "☐",
 escape(item['text'])
 ) for item in self.items))
my_todo = Todo()
my_todo.add("Buy milk", False)
my_todo.add("Do homework", False)
my_todo.add("Play video games", True)
my_todo

Will render:

  1. ☐ Buy milk
  2. ☐ Do homework
  3. ☑ Play video games
Udi
  • 30.8k
  • 9
  • 105
  • 134

AltStyle によって変換されたページ (->オリジナル) /