我有一个工作的 Selenium 程序,其中包含以下代码:
nxt_page = driver.find_element_by_class_name('btn--alt')
print(type(nxt_page))
if nxt_page:
driver.execute_script('arguments[0].scrollIntoView();', nxt_page)
print(type(nxt_page))
nxt_page.click()
(参见 Scraping Duckduckgo with Python 3.6)
程序运行时,显示两条打印语句
<class 'selenium.webdriver.remote.webelement.WebElement'>
<class 'selenium.webdriver.remote.webelement.WebElement'>
问题:如果你使用一个对象作为[if条件],例如
if OBJECT:
print('found')
Python 是简单地用 bool(OBJECT)
代替条件吗?
如果 OBJECT == None
,bool(OBJECT)
是否总是为 False?我不认为程序员可以篡改它。然后你可以等效地写
if nxt_page is not None:
ect.
在发布此内容之前,我刚刚发现 Boolean value of objects in Python ,这当然有帮助。
最佳答案
documentation对于如何在 boolean 上下文中评估值非常清楚:
In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are interpreted as false:
False
,None
, numeric zero of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and frozensets). All other values are interpreted as true. User-defined objects can customize their truth value by providing a__bool__()
method.
关于python - Python if 语句是否隐式地将 bool 应用于条件中找到的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49908828/