Sto scrivendo il mio contenitore, che deve consentire l'accesso a un dizionario all'interno tramite chiamate di attributi. L'uso tipico del contenitore sarebbe come questo:
dict_container = DictContainer()
dict_container['foo'] = bar
...
print dict_container.foo
So che potrebbe essere stupido scrivere qualcosa del genere, ma questa è la funzionalità che devo fornire. Stavo pensando di implementarlo nel modo seguente:
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"
Non sono sicuro se la nidificazione di tentativi / eccezioni sia una buona pratica, quindi un altro modo sarebbe usare hasattr()e 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")
O per usarne uno e provare a catturare il blocco in questo modo:
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")
Quale opzione è più pitonica ed elegante?
if 'foo' in dict_container:. Amen.