假设我有以下 Python 代码:
x = some_product()
name = x.name
first_child = x.child_list[0]
link = x.link
id = x.id
当 x.child_list 为 None 时,第 3 行可能会出现问题。这显然给了我一个TypeError,表示:
'NoneType' Object has no attribute '_____getitem_____'
我想做的是,每当 x.child_list[0] 给出一个 TypeError 时,只需忽略该行并转到下一行,即“< strong>link = x.link"...
所以我猜是这样的:
try:
x = some_product()
name = x.name
first_child = x.child_list[0]
link = x.link
id = x.id
Except TypeError:
# Pass, Ignore the statement that gives exception..
我应该在 Except block 下放什么? 还是有其他方法可以做到这一点?
我知道我可以使用 If x.child_list is not None: ...,但我的实际代码要复杂得多,我想知道是否有更多 pythonic 的方法来做这个
最佳答案
你想到的是这个:
try:
x = some_product()
name = x.name
first_child = x.child_list[0]
link = x.link
id = x.id
except TypeError:
pass
但是,最好的做法是在 try/catch
block 中放置尽可能少的内容:
x = some_product()
name = x.name
try:
first_child = x.child_list[0]
except TypeError:
pass
link = x.link
id = x.id
但是,您真正在这里应该做的是完全避免try/catch
,而是做这样的事情:
x = some_product()
name = x.name
first_child = x.child_list[0] if x.child_list else "no child list!"
# Or, something like this:
# first_child = x.child_list[0] if x.child_list else None
link = x.link
id = x.id
当然,您的选择最终取决于您想要的行为——您是否要保留 first_child
未定义,等等。
关于Python 尝试/捕获 : simply go to next statement when Exception,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22736412/