私は自分のコンテナを作成しています。このコンテナは、属性呼び出しによって内部の辞書にアクセスできるようにする必要があります。コンテナの一般的な使用法は次のようになります。
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] KeyErrorを除く:print"オブジェクトにはそのような属性がありません"
ネストされたtry/exceptブロックが適切かどうかわからないため、別の方法として<を使用します。 code> hasattr()およびhas_key()
:
def __getattribute __(self、item):if hasattr(self、item):オブジェクトを返します。 __getattribute __(item)else:if self.dict.has_key(item):return self.dict [item] else:raise AttributeError(&quot; some Customized error&quot;)
または使用するには
def __getattribute __(self、item):if hasattr(self、item):return object .__ getattribute __(item)else:try:returnself。 KeyErrorを除くdict[item]:raise AttributeError(&quot; some Customized error&quot;)
どのオプションが最もP ythonicでエレガントですか?