我正在寻找一种更优雅的方式来声明函数可能返回的变量值,None并且在函数调用之后存在链接方法.
在下面的示例中,我使用BeautifulSoup传递HTML文档,如果找不到我要查找的元素,则返回初始函数调用None.然后链接的方法会破坏代码,因为.string它不是None对象的方法.
这一切都有意义,但我想知道是否有更简洁的方法来编写这些不会破坏None值的变量声明.
# I want to do something like this but it throws error if soup.find returns
# none because .string is not a method of None.
title = soup.find("h1", "article-title").string or "none"
# This works but is both ugly and inefficient
title = "none" if soup.find("h1", "article-title") is None else soup.find("h1", "article-title").string
# So instead I'm using this which feels clunky as well
title = soup.find("h1", "article-title")
title = "none" if title is None else title.string
Run Code Online (Sandbox Code Playgroud)
有更好的方法吗?
您可以使用getattr内置函数提供默认值,以防在给定对象中找不到所需的属性:
title = getattr(soup.find("h1", "article-title"), "string", "none")
Run Code Online (Sandbox Code Playgroud)
或者,您可以使用try statement:
try:
title = soup.find("h1", "article-title").string
except AttributeError:
title = "none"
Run Code Online (Sandbox Code Playgroud)
我认为第一种方法更优雅。
| 归档时间: |
|
| 查看次数: |
801 次 |
| 最近记录: |