2009-08-27 121 views
4

现在我正在使用python。所以,关于字典.... 一个问题,假设我有一个字典是使用类属性获取字典

config = {'account_receivable': '4', 'account_payable': '5', 'account_cogs': '8', 'accoun 
t_retained_earning': '9', 'account_income': '6', 'account_expense': '31', 'durat 
ion': 2, 'financial_year_month': 9, 'financial_year_day': 15, 'account_cash': '3 
', 'account_inventory': '2', 'account_accumulated_depriciation': '34', 'account_ 
depriciation_expense': '35', 'account_salary_expense': '30', 'account_payroll_pa 
yable': '68', 'account_discount': '36', 'financial_year_close': '2008-08-08'} 

如果打印 - >配置[“account_receivable”]会返回其对应的值4

,但我想通过这种方式访问​​它 - > config.account_receivable然后它会返回相应的值

我该如何实现这个? 如果任何一个可以请帮我

BR // 纳兹穆尔

回答

12

为此,罗很多年前,我发明了简单的Bunch成语;实施Bunch一个简单的方法是:

class Bunch(object): 
    def __init__(self, adict): 
    self.__dict__.update(adict) 

如果config是一个字典,你不能使用config.account_receivable - 这是绝对不可能的,因为字典不该属性,期。但是,您可以包装config一个Bunch

cb = Bunch(config) 

,然后访问cb.config_account你的心脏的内容!

编辑:如果你想在Bunch属性分配也影响原有dict(在这种情况下config),使如cb.foo = 23会做config['foo'] = 23,你需要一个性能稍微不同的实施Bunch

class RwBunch(object): 
    def __init__(self, adict): 
    self.__dict__ = adict 

通常情况下,普通Bunch是首选,正是因为,实例化后,Bunch实例和dict这是“引”的是完全解耦 - 对其中任何一个的改变都不会影响另一个;而这种脱钩通常是所期望的。

当你想“耦合”效应,那么RwBunch是让他们的方式:有了它,每个属性设置或删除的实例将固有设置或从dict删除的项目,和,反之亦然,设置或删除dict中的项目将固有地设置或删除实例中的属性。

0

嗯,你可以带着一帮对象做到这一点。

class Config(object): 
    pass 

config = Config() 
config.account_receivable = 4 
print config.account_receivable 

显然你可以扩展这个类来为你做更多的事情。例如定义__init__,以便您可以使用参数创建它,也可以使用默认值。

您也可以使用namedtuplepython 2.4/2.5 link)。这是专门用于保存结构化记录的数据结构。

from collections import namedtuple 
Config = namedtuple('Config', 'account_receivable account_payable') # etc -- list all the fields 
c = Config(account_receivable='4', account_payable='5') 
print c.account_receivable 

使用namedtuples,您无法在设置值后更改值。

2

您需要使用Python的special methods之一。

class config(object): 
    def __init__(self, data): 
     self.data = data 
    def __getattr__(self, name): 
     return self.data[name] 


c = config(data_dict) 
print c.account_discount 
-> 36 
+0

非常感谢 – 2009-08-27 03:51:30

7

你可以用collections.namedtuple做到这一点:

from collections import namedtuple 
config_object = namedtuple('ConfigClass', config.keys())(*config.values()) 
print config_object.account_receivable 

您可以了解更多关于namedtuple这里:

http://docs.python.org/dev/library/collections.html

0

你也可以继承字典从自身退换货品未定义的属性:

class AttrAccessibleDict(dict): 
    def __getattr__(self, key): 
     try: 
      return self[key] 
     except KeyError:  
      return AttributeError(key) 

config = AttrAccessibleDict(config) 
print(config.account_receivable) 

您还可能要重写一些其他的方法为好,如__setattr____delattr____str____repr__copy