我正在编写自己的容器,该容器需要通过属性调用来访问内部的字典。容器的典型用法如下:
dict_container = DictContainer()
dict_container['foo'] = bar
...
print dict_container.foo
我知道写这样的东西可能很愚蠢,但这就是我需要提供的功能。我正在考虑通过以下方式实现此目的:
def __getattribute__(self, item):
try:
return object.__getattribute__(item)
except AttributeError:
try:
return self.dict[item]
except KeyError:
print "The object doesn't have such attribute"
我不确定嵌套的try / except块是否是一个好习惯,所以另一种方法是使用hasattr()
and has_key()
:
def __getattribute__(self, item):
if hasattr(self, item):
return object.__getattribute__(item)
else:
if self.dict.has_key(item):
return self.dict[item]
else:
raise AttributeError("some customised error")
或者使用其中之一,然后尝试使用catch块,如下所示:
def __getattribute__(self, item):
if hasattr(self, item):
return object.__getattribute__(item)
else:
try:
return self.dict[item]
except KeyError:
raise AttributeError("some customised error")
哪个选项最适合pythonic和优雅?
if 'foo' in dict_container:
。阿们