Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Вивчайте Challenge: Building a Plugin Interface | ABCs in Depth
Python Abstract Base Classes
Секція 2. Розділ 5
single

single

Challenge: Building a Plugin Interface

Свайпніть щоб показати меню

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"
Завдання

Проведіть, щоб почати кодувати

  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.

Рішення

Switch to desktopПерейдіть на комп'ютер для реальної практикиПродовжуйте з того місця, де ви зупинились, використовуючи один з наведених нижче варіантів
Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 2. Розділ 5
single

single

Запитати АІ

expand

Запитати АІ

ChatGPT

Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат

some-alt