Naposledy aktivní 10 months ago

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

timmy revidoval tento gist 10 months ago. Přejít na revizi

1 file changed, 22 insertions

custom_dictionary_class_instance.py(vytvořil soubor)

@@ -0,0 +1,22 @@
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'}
11 + # 建立一個類的實例,使用字典來初始化物件
12 + custom_dict = CustomDictionary(my_dict)
13 +
14 + # 列印字典
15 + print("字典:", my_dict)
16 + # 列印類的實例
17 + print("物件:", custom_dict)
18 + # 列印類的屬性
19 + print("屬性:", custom_dict.custom_property)
20 + # 列印屬性的值
21 + print("屬性的值:", custom_dict.custom_property)
22 +
Novější Starší