Piszę własny kontener, który musi dać dostęp do słownika wewnątrz poprzez wywołania atrybutów. Typowe zastosowanie kontenera wyglądałoby następująco:
dict_container = DictContainer()
dict_container['foo'] = bar
...
print dict_container.foo
Wiem, że pisanie czegoś takiego może być głupie, ale taką funkcjonalność muszę zapewnić. Myślałem o wdrożeniu tego w następujący sposób:
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"
Nie jestem pewien, czy zagnieżdżone bloki try / except są dobrą praktyką, więc innym sposobem byłoby użycie hasattr()i 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")
Lub użyj jednego z nich i jednego spróbuj złapać blok w ten sposób:
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")
Która opcja jest najbardziej pytoniczna i elegancka?
if 'foo' in dict_container:. Amen.