码迷,mamicode.com
首页 > 编程语言 > 详细

Python的高级特性11:拓展基本数据类型(dict)

时间:2015-07-23 23:28:16      阅读:228      评论:0      收藏:0      [点我收藏+]

标签:

字典的创建有两种方式,如果出现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

 

 

 

Python的高级特性11:拓展基本数据类型(dict)

标签:

原文地址:http://www.cnblogs.com/alexkn/p/4672023.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!