Abschnitt 1. Kapitel 4
single
Challenge: Your First ABC
Swipe um das Menü anzuzeigen
Aufgabe
Wischen, um mit dem Codieren zu beginnen
You are building the foundation of a reporting system. Your task is to define an abstract base class that enforces a consistent interface across all report types.
- Import
ABCandabstractmethodfrom theabcmodule. - Define an abstract class
BaseReport(ABC)with two abstract methods:generate(self, data)– produces and returns the report content as a string;get_format(self)– returns the report format name as a string (e.g."CSV","JSON").
- Define a concrete class
CsvReport(BaseReport)that:- implements
generate(self, data)–datais a list of dicts; returns a CSV string where the first line is the comma-joined keys of the first dict, and the second line is the comma-joined values of the first dict (convert each value tostr); - implements
get_format(self)that returns"CSV".
- implements
- Create an instance of
CsvReportcalledcsv_report. - Store the result of
csv_report.get_format()in a variable calledreport_format. - Store the result of
csv_report.generate([{"id": "R-001", "amount": "4500.0", "status": "approved"}])in a variable calledreport_output. - Print
report_formatandreport_output.
Lösung
War alles klar?
Danke für Ihr Feedback!
Abschnitt 1. Kapitel 4
single
Fragen Sie AI
Fragen Sie AI
Fragen Sie alles oder probieren Sie eine der vorgeschlagenen Fragen, um unser Gespräch zu beginnen