私は自分のコンテナを書いています。これは、属性呼び出しによって内部の辞書へのアクセスを提供する必要があります。コンテナの一般的な使用法は次のとおりです。
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"
私は別の方法を使用することですので、必ずブロックを除いて、ネストされた試しが/良い練習しているかどうかではないんだhasattr()と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")
または、そのうちの1つを使用して、次のように1つの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:ます。アーメン。