我正在編寫自己的容器,它需要通過屬性調用來訪問內部的字典。容器的典型用法是這樣的:
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 "The object doesn"t have such attribute"
我不確定嵌套的 try/except 塊是否是一個好習慣,所以另一種方法是使用 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(“一些自定義錯誤”)
或者使用一個其中一個 try catch 塊是這樣的:
def __getattribute__(self, item): if hasattr(self, item): return object.__getattribute__(item) else: try: return self. dict[item] except KeyError: raise AttributeError("some Customized error")
哪個選項最P韻味優雅?