最後活躍 10 months ago

這段程式碼展示了如何使用 Mixin 類別來提供額外功能。GraphicMixin 提供 draw() 方法,而 ColorMixin 提供 set_color() 方法,ColoredGraphic 繼承這兩個 Mixin,使其具備繪圖與設定顏色的功能。這種設計可以在不影響主要類別結構的情況下,為不同類別添加額外行為。

修訂 ccaca6c699cfca57f2ec07d8cb31f4ff36331abd

colored_graphic_mixin.py 原始檔案
1class GraphicMixin:
2 def draw(self):
3 print("Drawing the graphic")
4
5class ColorMixin:
6 def set_color(self, color):
7 self.color = color
8 print(f"Setting color to {color}")
9
10class ColoredGraphic(ColorMixin, GraphicMixin):
11 pass
12
13# 使用 ColoredGraphic 類
14colored_graphic = ColoredGraphic()
15colored_graphic.draw() # 呼叫 GraphicMixin 的方法
16colored_graphic.set_color("red") # 呼叫 ColorMixin 的方法
17
18