custom_dictionary_class_instance.py
· 578 B · Python
Raw
class CustomDictionary(dict):
def __init__(self, dictionary):
super().__init__(dictionary)
@property
def custom_property(self):
return self
# 建立一個普通字典
my_dict = {'key1': 'value1', 'key2': 'value2'}
# 建立一個類的實例,使用字典來初始化物件
custom_dict = CustomDictionary(my_dict)
# 列印字典
print("字典:", my_dict)
# 列印類的實例
print("物件:", custom_dict)
# 列印類的屬性
print("屬性:", custom_dict.custom_property)
# 列印屬性的值
print("屬性的值:", 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'} |
| 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 | |
| 23 |