最後活躍 10 months ago

這段程式碼定義了一個 CustomDictionary 類別,繼承 Python 內建的 dict,並添加了一個 custom_property 屬性。該屬性返回自身,使得 custom_dict.custom_property 能夠訪問完整的字典內容。這種設計可用於擴展字典功能,提供自訂方法或屬性,而不影響原始字典行為。

修訂 f6040fdd820c86e1afea41846c2a545c012e0478

custom_dictionary_class_instance.py 原始檔案
1class CustomDictionary(dict):
2 def __init__(self, dictionary):
3 super().__init__(dictionary)
4
5 @property
6 def custom_property(self):
7 return self
8
9# 建立一個普通字典
10my_dict = {'key1': 'value1', 'key2': 'value2'}
11# 建立一個類的實例,使用字典來初始化物件
12custom_dict = CustomDictionary(my_dict)
13
14# 列印字典
15print("字典:", my_dict)
16# 列印類的實例
17print("物件:", custom_dict)
18# 列印類的屬性
19print("屬性:", custom_dict.custom_property)
20# 列印屬性的值
21print("屬性的值:", custom_dict.custom_property)
22
23