使用类属性访问字典
现在我正在使用python.所以有一个关于字典的问题.... 假设我有一个命令
now I am working with python. So one question about dict .... suppose I have a dict that
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'}
如果打印-> config ['account_receivable'],它将返回其对应的值4
if print --> config['account_receivable'] it will return its corresponding value that 4
但是我想通过这种方式访问它-> config.account_receivable,然后它将返回对应的值
but I want to access it by that way--> config.account_receivable and then it will return it corresponding value
我该如何实现呢?
为此,很多年前,我发明了简单的Bunch
习惯用语.实现Bunch
的一种简单方法是:
For that purpose, lo that many years ago, I invented the simple Bunch
idiom; one simple way to implement Bunch
is:
class Bunch(object):
def __init__(self, adict):
self.__dict__.update(adict)
如果config
是字典,则不能使用config.account_receivable
,这是绝对不可能的,因为字典没有拥有该属性,句点.但是,您可以 将config
包装到Bunch
中:
If config
is a dict, you can't use config.account_receivable
-- that's absolutely impossible, because a dict doesn't have that attribute, period. However, you can wrap config
into a Bunch
:
cb = Bunch(config)
然后访问cb.config_account
您内心的内容!
and then access cb.config_account
to your heart's content!
编辑:如果您希望Bunch
上的属性分配也影响原始的dict
(在这种情况下为config
),例如cb.foo = 23
将执行config['foo'] = 23
,您需要一个完全不同的Bunch
实现:
Edit: if you want attribute assignment on the Bunch
to also affect the original dict
(config
in this case), so that e.g. cb.foo = 23
will do config['foo'] = 23
, you need a slighly different implementation of Bunch
:
class RwBunch(object):
def __init__(self, adict):
self.__dict__ = adict
通常,纯Bunch
是首选,完全是,因为 在实例化之后,Bunch
实例和从其启动"的dict
会完全解耦-更改为它们中的一个不影响另一个;而这种去耦通常是我们所希望的.
Normally, the plain Bunch
is preferred, exactly because, after instantiation, the Bunch
instance and the dict
it was "primed" from are entirely decoupled -- changes to either of them do not affect the other; and such decoupling, most often, is what's desired.
当您要做想要耦合"效果时,RwBunch
是获取效果的方法:使用它,实例上的每个属性设置或删除都将固有地设置或删除该项目. dict
,反之亦然,从dict
设置或删除项目将本质上从实例设置或删除属性.
When you do want "coupling" effects, then RwBunch
is the way to get them: with it, every attribute setting or deletion on the instance will intrinsically set or delete the item from the dict
, and, vice versa, setting or deleting items from the dict
will intrinsically set or delete attributes from the instance.