colored_graphic_mixin.py
· 448 B · Python
Исходник
class GraphicMixin:
def draw(self):
print("Drawing the graphic")
class ColorMixin:
def set_color(self, color):
self.color = color
print(f"Setting color to {color}")
class ColoredGraphic(ColorMixin, GraphicMixin):
pass
# 使用 ColoredGraphic 類
colored_graphic = ColoredGraphic()
colored_graphic.draw() # 呼叫 GraphicMixin 的方法
colored_graphic.set_color("red") # 呼叫 ColorMixin 的方法
| 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 | |
| 18 |