|
| 1 | +from abc import ABC, abstractmethod |
| 2 | + |
| 3 | +# Bad example |
| 4 | +# class Printer(ABC): |
| 5 | +# @abstractmethod |
| 6 | +# def print(self, document): |
| 7 | +# pass |
| 8 | + |
| 9 | +# @abstractmethod |
| 10 | +# def fax(self, document): |
| 11 | +# pass |
| 12 | + |
| 13 | +# @abstractmethod |
| 14 | +# def scan(self, document): |
| 15 | +# pass |
| 16 | + |
| 17 | + |
| 18 | +# class OldPrinter(Printer): |
| 19 | +# def print(self, document): |
| 20 | +# print(f"Printing {document} in black and white...") |
| 21 | + |
| 22 | +# def fax(self, document): |
| 23 | +# raise NotImplementedError("Fax functionality not supported") |
| 24 | + |
| 25 | +# def scan(self, document): |
| 26 | +# raise NotImplementedError("Scan functionality not supported") |
| 27 | + |
| 28 | + |
| 29 | +# class ModernPrinter(Printer): |
| 30 | +# def print(self, document): |
| 31 | +# print(f"Printing {document} in color...") |
| 32 | + |
| 33 | +# def fax(self, document): |
| 34 | +# print(f"Faxing {document}...") |
| 35 | + |
| 36 | +# def scan(self, document): |
| 37 | +# print(f"Scanning {document}...") |
| 38 | + |
| 39 | + |
| 40 | +# Good example |
| 41 | +class Printer(ABC): |
| 42 | + @abstractmethod |
| 43 | + def print(self, document): |
| 44 | + pass |
| 45 | + |
| 46 | + |
| 47 | +class Fax(ABC): |
| 48 | + @abstractmethod |
| 49 | + def fax(self, document): |
| 50 | + pass |
| 51 | + |
| 52 | + |
| 53 | +class Scanner(ABC): |
| 54 | + @abstractmethod |
| 55 | + def scan(self, document): |
| 56 | + pass |
| 57 | + |
| 58 | + |
| 59 | +class OldPrinter(Printer): |
| 60 | + def print(self, document): |
| 61 | + print(f"Printing {document} in black and white...") |
| 62 | + |
| 63 | + |
| 64 | +class NewPrinter(Printer, Fax, Scanner): |
| 65 | + def print(self, document): |
| 66 | + print(f"Printing {document} in color...") |
| 67 | + |
| 68 | + def fax(self, document): |
| 69 | + print(f"Faxing {document}...") |
| 70 | + |
| 71 | + def scan(self, document): |
| 72 | + print(f"Scanning {document}...") |
0 commit comments