Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære Challenge: Building a Plugin Interface | ABCs in Depth
Python Abstract Base Classes
Seksjon 2. Kapittel 5
single

single

Challenge: Building a Plugin Interface

Sveip for å vise menyen

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"
Oppgave

Sveip for å begynne å kode

  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.

Løsning

Switch to desktopBytt til skrivebordet for virkelighetspraksisFortsett der du er med et av alternativene nedenfor
Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 2. Kapittel 5
single

single

Spør AI

expand

Spør AI

ChatGPT

Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår

some-alt