Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprende Challenge: Building a Plugin Interface | ABCs in Depth
Python Abstract Base Classes
Sección 2. Capítulo 5
single

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

  1. Import ABC and abstractmethod from abc.
  2. 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.
  3. Add a __subclasshook__ classmethod to ExporterPlugin that returns True if the subclass has both export and get_format in its MRO, otherwise returns NotImplemented.
  4. Define MarkdownExporter(ExporterPlugin) that:
    • implements export(self, data) – returns a markdown list where each item in data is prefixed with "- ", joined by newlines;
    • implements get_format(self) that returns "Markdown".
  5. Register LegacyXmlExporter as a virtual subclass of ExporterPlugin using register().
  6. Create instances: md_exporter = MarkdownExporter() and xml_exporter = LegacyXmlExporter().
  7. Store isinstance(md_exporter, ExporterPlugin) in md_is_plugin and isinstance(xml_exporter, ExporterPlugin) in xml_is_plugin.
  8. Print both variables.

Solución

Switch to desktopCambia al escritorio para practicar en el mundo realContinúe desde donde se encuentra utilizando una de las siguientes opciones
¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 2. Capítulo 5
single

single

Pregunte a AI

expand

Pregunte a AI

ChatGPT

Pregunte lo que quiera o pruebe una de las preguntas sugeridas para comenzar nuestra charla

some-alt