-
Notifications
You must be signed in to change notification settings - Fork 0
/
dict_unchange.py
65 lines (44 loc) · 1.16 KB
/
dict_unchange.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# -*- coding: utf-8 -*-
from types import MappingProxyType
class DictUnchange(object):
"""
字典 不可变
"""
def __init__(self):
self.item = dict()
def __call__(self, key, value):
self.item[key] = value
return MappingProxyType(self.item)
def dict_unchange(key, value):
item = dict()
item[key] = value
try:
result = MappingProxyType(item)
except TypeError as err:
raise err
return result
item = dict()
def dict_key_set_one(key, value):
if key in item:
print("此 key 已被设置过,请设置新的key值")
return
item[key] = value
return MappingProxyType(item)
if __name__ == '__main__':
d = DictUnchange()
dd = d('animal', 'giraffe')
print(dd, type(dd))
try:
dd['animal'] = 'cat'
except TypeError as e:
print(e)
d_1 = dict_unchange('fruit', 'apple')
print(d_1, type(d_1))
print(d_1['fruit'])
try:
d_1['fruit'] = 'orange'
except TypeError as e:
print("d_1 字典不能更改")
ddd = dict_key_set_one('code', 'python')
dict_key_set_one('code', 'c')
print(ddd, type(ddd))