字典的创建有两种方式,如果出现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)
运行结果是:
/System/Library/Frameworks/Python.framework/Versions/3.4/bin/python3 /Users/lsf/PycharmProjects/py3Project/test3.py {'sex': 'male', 'name': 'alex'} alex Process finished with exit code 0