Python dict是一个对象吗? [英] Is Python dict an Object?

查看:77
本文介绍了Python dict是一个对象吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的dict:

>>> my_dict = {u'2008': 6.57, u'2009': 4.89, u'2011': 7.74,
...            u'2010': 7.44, u'2012': 7.44}

使用has_key输出:

>>> my_dict.has_key(unicode(2012))
True

使用hasattr输出:

>>> hasattr(my_dict, unicode(2012))
False

我不明白为什么这种行为会有所不同. 我用Google搜索,发现这是因为dict和对象不同.

I couldn't understand why this behaves differently. I googled and found out that it is because dict and objects are different.

但是,我仍然无法正确理解其中的区别.

But, still I couldn't understand the difference properly.

(顺便说一句:我正在使用python 2.7)

(BTW : I am using python 2.7)

推荐答案

dict实例也是对象.但是它们的键只是不作为属性公开.

dict instances are objects too. But their keys are just not exposed as as attributes.

将键公开为属性(太或不代替项访问)将导致名称空间污染;例如,您将永远无法使用has_key键. has_key已经 是词典的属性:

Exposing the keys as attributes (too or instead of item access) would lead to namespace pollution; you'd never be able to use a has_key key, for example. has_key is already an attribute on dictionaries:

>>> hasattr({}, 'has_key')
True
>>> {}.has_key
<built-in method has_key of dict object at 0x7fa2a8461940>

对象的属性和词典的内容是两个分开的事物,并且分开是有意的.

Attributes of objects and the contents of dictionaries are two separate things, and the separation is deliberate.

您始终可以使用 __getattr__()挂钩方法:

You can always subclass dict to add attribute access using the __getattr__() hook method:

class AttributeDict(dict):
    def __getattr__(self, name):
        if name in self:
            return self[name]
        raise AttributeError(name)

演示:

>>> demo = AttributeDict({'foo': 'bar'})
>>> demo.keys()
['foo']
>>> demo.foo
'bar'

类别上的

现有属性优先:

>>> demo['has_key'] = 'monty'
>>> demo.has_key
<built-in method has_key of AttributeDict object at 0x7fa2a8464130>

这篇关于Python dict是一个对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆