All gists matching topic object-oriented-programming

timmy / Python 自訂字典類別

0 curtidas
0 bifurcações
1 arquivos
Última atividade 10 months ago
這段程式碼定義了一個 CustomDictionary 類別,繼承 Python 內建的 dict,並添加了一個 custom_property 屬性。該屬性返回自身,使得 custom_dict.custom_property 能夠訪問完整的字典內容。這種設計可用於擴展字典功能,提供自訂方法或屬性,而不影響原始字典行為。
1 class CustomDictionary(dict):
2 def __init__(self, dictionary):
3 super().__init__(dictionary)
4
5 @property
6 def custom_property(self):
7 return self
8
9 # 建立一個普通字典
10 my_dict = {'key1': 'value1', 'key2': 'value2'}

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):

timmy / Python 類別與繼承示範

0 curtidas
0 bifurcações
1 arquivos
Última atividade 10 months ago
這段程式碼示範了 Python 的類別繼承機制,透過 Person(人)和 Employee(員工)類別,展現子類別如何繼承父類別的屬性與方法,並添加自己的功能。
1 # 定義 Person 類別
2 class Person:
3 # 定義建構子
4 def __init__(self, name):
5 # 設定人的名字
6 self.name = name
7
8 # 定義取得人的名字的方法
9 def get_name(self):
10 """取得人的名字"""

timmy / 策略模式在購物車計價中的應用

1 curtidas
0 bifurcações
1 arquivos
Última atividade 10 months ago
這段程式碼實作「策略模式(Strategy Pattern)」,用於計算購物車的總金額,並允許 根據不同的定價策略(如正常價格或折扣價格) 來計算最終價格。
1 from abc import ABC, abstractmethod
2
3 # 策略介面
4 class PricingStrategy(ABC):
5 @abstractmethod
6 def calculate_price(self, price):
7 pass
8
9 # 具體策略類
10 class NormalStrategy(PricingStrategy):
Próximo Anterior