>>> from env_helper import info; info()
页面更新时间: 2024-04-04 21:02:25
运行环境:
    Linux发行版本: Debian GNU/Linux 12 (bookworm)
    操作系统内核: Linux-6.1.0-18-amd64-x86_64-with-glibc2.36
    Python版本: 3.11.2

13.10. 拓展基本数据类型(dict)

字典的创建有两种方式,如果出现In [26]这样的赋值方式就会报错。

In [17]: s['name'] = 'alex'

In [18]: s['sex'] = 'male'

In [19]: s
Out[19]: {'name': 'alex', 'sex': 'male'}

In [20]: s = {'name':'alex','sex':'male'}

In [21]: s
Out[21]: {'name': 'alex', 'sex': 'male'}

In [22]: t = {}

In [23]: t['name'] = 'lilei'

In [24]: t['sex'] = 'male'

In [25]: t
Out[25]: {'name': 'lilei', 'sex': 'male'}

In [26]: t.name = 'hanmeimei'
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-26-62e0b27ded5b> in <module>()
----> 1 t.name = 'hanmeimei'

AttributeError: 'dict' object has no attribute 'name'

但我这个人很固执,就对这种方式情有独钟,迫切希望Python可以拓展这个属性,该怎么办呢?最好的办法就是自己来拓展。

t.name = ‘hanmeimei’ 这样的set方式明显是__setter__行为,那么我只需要重写__setter__方法就可以了。

>>> class StrongerDict(dict):
>>>     def __getattr__(self, key):
>>>         return self[key]
>>>
>>>     def __setattr__(self, key, value):
>>>         self[key] = value
>>>
>>>     def __call__(self, key):
>>>         return self[key]
>>>
>>>
>>> s = StrongerDict()
>>> #__setattr__方法
>>> s.name = 'alex'
>>> #dict本身赋值方法不受影响,因为重写的是__setattr__方法
>>> s['sex'] = 'male'
>>> print(s)
>>> #__getattr__方法
>>> print(s.name)
{'name': 'alex', 'sex': 'male'}
alex