timmy / Python 自訂字典類別
0 Kedvelések
0 forkok
1 fájlok
Utoljára aktív 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'} |
Újabb
Régebbi