Skip to main content
 首页 » 编程设计

python之使用点符号获取内部值

2024年10月17日7JeffreyZhao

我有一本字典:

d = {'time': {36.0: 'mo'}, 'amount': {200.0: '$'}} 

每个键(例如 'time')只有一个值(例如 {36.0 'mo'})

我想通过以下方式访问 36.0

result = d.time 

通过做 200.0

result = d.amount 

我该怎么做?到目前为止,我有:

class Bunch(object): 
  def __init__(self, adict): 
    self.__dict__.update(adict) 
 
x = Bunch(d) 
print x.time 

产生 {36.0: 'mo'} 而不是 36.0。

请您参考如下方法:

在确保数据键和 dict 方法之间没有名称冲突之后,我将 dict 子类化并覆盖 __getattr__。

d = {'time': {36.0: 'mo'}, 'amount': {200.0: '$'}} 
 
class Bunch(dict): 
    def __getattr__(self, attr): 
        try: 
            val = self[attr] 
            return next(iter(val)) 
        except KeyError: 
            raise AttributeError(attr) 
 
x =  Bunch(d) 
x.time # 36.0