假设我有以下Python代码:
x = some_product()
name = x.name
first_child = x.child_list[0]
link = x.link
id = x.id
Run Code Online (Sandbox Code Playgroud)
当x.child_list为None时,第3行可能会出现问题.这显然给了我一个TypeError,说:
'NoneType' Object has no attribute '_____getitem_____'
Run Code Online (Sandbox Code Playgroud)
我想要做的是,每当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..
Run Code Online (Sandbox Code Playgroud)
我应该在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
Run Code Online (Sandbox Code Playgroud)
但是,最好的做法是尽可能少地放入try/catch块中:
x = some_product()
name = x.name
try:
first_child = x.child_list[0]
except TypeError:
pass
link = x.link
id = x.id
Run Code Online (Sandbox Code Playgroud)
但是,你真正应该做的就是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
Run Code Online (Sandbox Code Playgroud)
当然,您的选择最终取决于您期望的行为 - 您是否希望保留first_child未定义或未定义等.
| 归档时间: |
|
| 查看次数: |
8287 次 |
| 最近记录: |