如何在python中使访问成为散列?

如何在python中使访问成为散列?,python,hash,Python,Hash,我知道这个问题听起来很基本。但是我用谷歌找不到它。我知道有些字典看起来像 o = { 'a': 'b' } 它们可以通过o['a']访问。但是作为o.a访问的被称为什么?我知道它们是存在的,因为我使用的是OptPass库,它会返回一个可以访问的对象。您不能使用“.”来访问dict,除非您通过从dict派生并通过“.”符号实现自己的dict类型,并通过实现\uu getattribute\uuuuuuuuuu()API,负责执行属性样式访问 请参见名称。属性是Python中的对象访问,而不是

我知道这个问题听起来很基本。但是我用谷歌找不到它。我知道有些字典看起来像

o = {
  'a': 'b'
}

它们可以通过
o['a']
访问。但是作为
o.a
访问的被称为什么?我知道它们是存在的,因为我使用的是OptPass库,它会返回一个可以访问的对象。

您不能使用“.”来访问dict,除非您通过从dict派生并通过“.”符号实现自己的dict类型,并通过实现
\uu getattribute\uuuuuuuuuu()
API,负责执行属性样式访问


请参见

名称。属性
是Python中的对象访问,而不是dict访问

您可以在“新样式类”中作为字典访问变量。不过我觉得你得小心一点

>>> class C(object): # python 2 code, inheriting from 'object' is automatic in 3
    a = 5
    def __init__(self):
        self.j = 90


>>> c = C()
>>> c.__dict__
{'j': 90}
>>> print c.j
90
>>> print c.a
5
请注意,字典中出现了“j”,而“a”没有出现。这似乎与它们的初始化方式有关。我对这种行为有点困惑,我不介意一位大师的解释:D

编辑:

再多玩一点,很明显他们为什么会选择上面的行为(但还是有点奇怪)

>>> class C(object):
    a = 5
    def __init__(self):
        self.j = 90
        self.funct = range # assigning a variable to a function

>>> c = C()
>>> c.__dict__
{'j': 90, 'funct': <built-in function range>}
>>C类(对象):
a=5
定义初始化(自):
self.j=90
self.funct=范围#将变量分配给函数
>>>c=c()
>>>c.uu dict__
{'j':90,'funct':}
我认为它将类对象(对于每个类都是相同的)与新的类成员(例如在init中启动的成员)分离

>>> c.newvar = 234
>>> c.__dict__
{'j': 90, 'newvar': 234, 'funct': <built-in function range>}
>c.newvar=234
>>>c.uu dict__
{'j':90,'newvar':234,'funct':}

你可以看到它正在构建一个字典!希望这能有所帮助:在我看来,D

就像是
optpasse
模拟了一个隐藏的
dict
的属性接口,但是有一个标准库做了类似的事情,如果不是真正的字典的话:。我不能谈论这里介绍的其他机制。

是您希望与
\u uu setattr_
一起实现的方法。下面是一个非常简单的示例(无错误检查等),它显示了一个同时允许字典样式和属性样式访问的对象:

Missing = object()

class AttrElem(object):
    def __init__(self, **kwds):
        self.items = kwds.copy()
    def __getitem__(self, name):
        result = self.items.get(name, Missing)
        if result is not Missing:
            return result
        raise KeyError("key %r not found" % name)
    def __setitem__(self, name, value):
        self.items[name] = value
    def __getattr__(self, name):
        result = self.items.get(name, Missing)
        if result is not Missing:
            return result
        raise AttributeError("attribute %r not found" % name)
    def __setattr__(self, name, value):
        if name == 'items':
            object.__setattr__(self, name, value)
        else:
            self.items[name] = value
    def __repr__(self):
        return 'AttrElem(%s)' % ', '.join(
                ["%s:%s" % (k, v) for k, v in self.items.items()]
                )
在使用中,它看起来像这样:

example = AttrElem(this=7, that=9)
print(example)
example.those = 'these'
example['who'] = 'Guido'
print(example)

正如您从代码中看到的那样,
\uu getitem\uuuuuuuu
\uuuu getattr\uuuuuu
都非常相似,只是在找不到目标时引发的异常不同。

我明白了。好的,谢谢。我只是想确保我以最好的方式编码。今天刚开始学习python,我正在边学习。