可以说我有以下Python代码:
x = some_product()
name = x.name
first_child = x.child_list[0]
link = x.link
id = x.id
当 x.child_list 为无时,第3行可能会出现问题。这显然给了我 TypeError ,说:
'NoneType' Object has no attribute '_____getitem_____'
我想做的是,每当 x.child_list [0] 给出 TypeError 时,只需忽略该行并转到下一行,即“ 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块下放什么?
还是有其他方法可以做到这一点?
我知道我可以使用如果x.child_list不是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
块中: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 - Python尝试/捕获: simply go to next statement when Exception,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22736412/