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

single

Challenge: Building a Plugin Interface

Swipe um das Menü anzuzeigen

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

Wischen, um mit dem Codieren zu beginnen

  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ösung

Switch to desktopWechseln Sie zum Desktop, um in der realen Welt zu übenFahren Sie dort fort, wo Sie sind, indem Sie eine der folgenden Optionen verwenden
War alles klar?

Wie können wir es verbessern?

Danke für Ihr Feedback!

Abschnitt 2. Kapitel 5
single

single

Fragen Sie AI

expand

Fragen Sie AI

ChatGPT

Fragen Sie alles oder probieren Sie eine der vorgeschlagenen Fragen, um unser Gespräch zu beginnen

some-alt