当前位置 : 主页 > 编程语言 > python >

Python小记——不可变映射类型

来源:互联网 收集:自由互联 发布时间:2022-06-24
In [ 5 ]: from types import MappingProxyType In [ 6 ]: d = { 1 : 'a' } In [ 7 ]: d_proxy = MappingProxyType ( d ) In [ 8 ]: d_proxy [ 1 ] Out [ 8 ]: 'a' In [ 9 ]: d_proxy Out [ 9 ]: mappingproxy ({ 1 : 'a' }) In [ 10 ]: d_proxy [ 2 ] - - -
In [5]: from types import MappingProxyType

In [6]: d = {1:'a'}

In [7]: d_proxy = MappingProxyType(d)

In [8]: d_proxy[1]
Out[8]: 'a'

In [9]: d_proxy
Out[9]: mappingproxy({1: 'a'})

In [10]: d_proxy[2]
------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-10-6f9dce4cd735> in <module>
----> 1 d_proxy[2]

KeyError: 2

In [11]: d_proxy[2] = 'x'
------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-11-bc17a9a62754> in <module>
----> 1 d_proxy[2] = 'x'

TypeError: 'mappingproxy' object does not support item assignment

In [12]: d[2] = 'x'

In [13]: d_proxy
Out[13]: mappingproxy({1: 'a', 2: 'x'})


上一篇:Python小记——增量赋值操作
下一篇:没有了
网友评论