Python 中嵌套的 try/except 塊是一種好的編程習慣嗎?

| | |

我正在編寫自己的容器,它需要通過屬性調用來訪問內部的字典。容器的典型用法是這樣的:

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韻味優雅?

Python 中嵌套的 try/except 塊是一種好的編程習慣嗎? __dict__: Questions

Python 中嵌套的 try/except 塊是一種好的編程習慣嗎? has_key: Questions

Shop

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Best laptop for Zoom

$499

Latest questions

NUMPYNUMPY

psycopg2: insert multiple rows with one query

12 answers

NUMPYNUMPY

How to convert Nonetype to int or string?

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Javascript Error: IPython is not defined in JupyterLab

12 answers

News

Wiki

Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | cv2.circle () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method