Sección 2. Capítulo 5
single
Challenge: Building a Plugin Interface
Desliza para mostrar el menú
You are building a plugin system for a data export tool. Plugins are registered with a central registry and must conform to a standard interface. Your task is to implement the ABC, two concrete plugins, and a virtual subclass registration.
You are given the following third-party class that you cannot modify:
class LegacyXmlExporter:
def export(self, data):
items = "".join(f"<item>{row}</item>" for row in data)
return f"<root>{items}</root>"
def get_format(self):
return "XML"
Tarea
Desliza para comenzar a programar
- Import
ABCandabstractmethodfromabc. - Define
ExporterPlugin(ABC)with two abstract methods:export(self, data)– takes a list and returns a string;get_format(self)– returns the format name as a string.
- Add a
__subclasshook__classmethod toExporterPluginthat returnsTrueif the subclass has bothexportandget_formatin its MRO, otherwise returnsNotImplemented. - Define
MarkdownExporter(ExporterPlugin)that:- implements
export(self, data)– returns a markdown list where each item indatais prefixed with"- ", joined by newlines; - implements
get_format(self)that returns"Markdown".
- implements
- Register
LegacyXmlExporteras a virtual subclass ofExporterPluginusingregister(). - Create instances:
md_exporter = MarkdownExporter()andxml_exporter = LegacyXmlExporter(). - Store
isinstance(md_exporter, ExporterPlugin)inmd_is_pluginandisinstance(xml_exporter, ExporterPlugin)inxml_is_plugin. - Print both variables.
Solución
¿Todo estuvo claro?
¡Gracias por tus comentarios!
Sección 2. Capítulo 5
single
Pregunte a AI
Pregunte a AI
Pregunte lo que quiera o pruebe una de las preguntas sugeridas para comenzar nuestra charla