Python中不可变映射类型有哪些特点?

2026-05-24 14:542阅读0评论SEO资源
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计157个文字,预计阅读时间需要1分钟。

Python中不可变映射类型有哪些特点?

pythonfrom types import MappingProxyType

d={1: 'a'}d_proxy=MappingProxyType(d)d_proxy[1]d_proxy

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中不可变映射类型有哪些特点?

本文共计157个文字,预计阅读时间需要1分钟。

Python中不可变映射类型有哪些特点?

pythonfrom types import MappingProxyType

d={1: 'a'}d_proxy=MappingProxyType(d)d_proxy[1]d_proxy

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中不可变映射类型有哪些特点?