Última atividade 10 months ago

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

timmy revisou este gist 10 months ago. Ir para a revisão

1 file changed, 17 insertions

colored_graphic_mixin.py(arquivo criado)

@@ -0,0 +1,17 @@
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):
11 + pass
12 +
13 + # 使用 ColoredGraphic 類
14 + colored_graphic = ColoredGraphic()
15 + colored_graphic.draw() # 呼叫 GraphicMixin 的方法
16 + colored_graphic.set_color("red") # 呼叫 ColorMixin 的方法
17 +
Próximo Anterior