2011-04-03 47 views
2

我知道这个问题听起来很基本。但我无法使用Google找到它。我知道有字典看起来像如何在python中访问哈希?

o = { 
    'a': 'b' 
} 

他们访问与o['a']。但是那些被称为o.a的访问者是什么?我知道它们的存在是因为我使用了optparse库,并且它返回了一个可访问的对象。

回答

2

使用类型的字典你不能访问“”除非你通过派生词典并通过'。'来提供访问来实现你自己的字典类型。通过实施负责执行属性样式访问的__getattribute__() API。

http://docs.python.org/reference/datamodel.html#object.__getattribute__

+0

我明白了。好的谢谢。只是想确保我以最好的方式进行编码。刚刚开始学习python,我正在学习。 – fent 2011-04-03 05:55:22

0

name.attribute对象访问在Python,不是字典访问

1

您可以访问的变量,如 “新样式类” 一本字典。我认为你必须小心谨慎。

>>> 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.newvar = 234 
>>> c.__dict__ 
{'j': 90, 'newvar': 234, 'funct': <built-in function range>} 

你可以看到它正在建设一个字典!希望这有助于:d

2

在我看来就像optparse模拟属性界面隐藏dict,但有文件做一些事有点类似一个标准库,如果没有真正的字典:collections.namedtuple。我不能对这里介绍的其他机制说话。

0

__getattr__是你要实现的方法,用__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) 

从代码__getitem____getattr__可以看出,两者都非常相似,只有当找不到目标时才会引发异常。