Python 使用class属性访问字典
现在我正在使用python。所以有一个关于dict的问题。。。。 假设我有一个口述Python 使用class属性访问字典,python,dictionary,Python,Dictionary,现在我正在使用python。所以有一个关于dict的问题。。。。 假设我有一个口述 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, '
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_Received'],它将返回其对应的值,该值为4
但我希望通过这种方式访问它-->config.account\u received,然后它将返回相应的值
如何实现这一点?好吧,你可以用一堆对象来实现
class Config(object):
pass
config = Config()
config.account_receivable = 4
print config.account_receivable
显然,您可以扩展这个类来为您做更多的事情。e、 g.定义\uuuu init\uuuu
,这样您就可以使用参数创建它,也可以使用默认值
您也可以使用()。这是一种专门为保存结构化记录而设计的数据结构
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时,一旦设置了值,就无法更改它们。请查看。您需要使用Python的一个值。
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
您可以使用collections.namedtuple执行此操作:
from collections import namedtuple
config_object = namedtuple('ConfigClass', config.keys())(*config.values())
print config_object.account_receivable
您可以在此处了解有关namedtuple的更多信息:
为了这个目的,很多年前,我发明了简单的
一堆成语;实现Bunch
的一种简单方法是:
class Bunch(object):
def __init__(self, adict):
self.__dict__.update(adict)
如果config
是一个dict,你就不能使用config.account\u received
——这是绝对不可能的,因为dict没有这个属性,period。但是,您可以将config
包装成一个Bunch
:
cb = Bunch(config)
class RwBunch(object):
def __init__(self, adict):
self.__dict__ = adict
然后访问cb.config\u帐户
,进入您的心扉
编辑:如果您希望串
上的属性赋值也影响原始的dict
(config
,在这种情况下),因此,例如cb.foo=23
将执行config['foo']=23
,您需要一个略微不同的串
实现:
cb = Bunch(config)
class RwBunch(object):
def __init__(self, adict):
self.__dict__ = adict
通常情况下,首选普通的Bunch
,这正是因为在实例化之后,Bunch
实例和它“启动”的dict
是完全解耦的——对其中任何一个的更改都不会影响另一个;而这种脱钩往往是人们所期望的
当您想要“耦合”效果时,RwBunch
是获得这些效果的方法:使用它,实例上的每个属性设置或删除都会从dict
中设置或删除该项,反之亦然,从dict
中设置或删除项目将本质上设置或删除实例中的属性。您可以将dict子类化,以从自身返回未定义属性的项目:
class AttrAccessibleDict(dict):
def __getattr__(self, key):
try:
return self[key]
except KeyError:
return AttributeError(key)
config = AttrAccessibleDict(config)
print(config.account_receivable)
您可能还希望覆盖其他一些方法,例如\uuuuuu setattr\uuuuuuu
,\uuuu delattr\uuuuuuuuuu
,\uuuuuu str\uuuuuuuu
,和复制