timmy / Python Mixin 類別設計
1 curtidas
0 bifurcações
1 arquivos
Última atividade 10 months ago
這段程式碼展示了如何使用 Mixin 類別來提供額外功能。GraphicMixin 提供 draw() 方法,而 ColorMixin 提供 set_color() 方法,ColoredGraphic 繼承這兩個 Mixin,使其具備繪圖與設定顏色的功能。這種設計可以在不影響主要類別結構的情況下,為不同類別添加額外行為。
| 1 | class GraphicMixin: |
| 2 | def draw(self): |
| 3 | print("Drawing the graphic") |
| 4 | |
| 5 | class ColorMixin: |
| 6 | def set_color(self, color): |
| 7 | self.color = color |
| 8 | print(f"Setting color to {color}") |
| 9 | |
| 10 | class ColoredGraphic(ColorMixin, GraphicMixin): |
Próximo
Anterior