什么时候在日常编码中使用它?我正在使用Python学习本教程 http://openbookproject.net/thinkcs/python/english2e/。我所指的是什么已被描述here http://openbookproject.net/thinkcs/python/english2e/ch04.html(页面中间),但我无法理解。我理解使用 True 和 False 的原则,但我不知道我们何时(或确实)实际使用bool()
在编写代码时在实践中发挥作用。如果你能举出日常的实际例子,会对我有帮助bool()
在代码中。
它允许您将任何 Python 值转换为布尔值。
有时你想存储其中一个True
or False
依赖于另一个 Python 对象。代替:
if python_object:
result = True
else:
result = False
你只需这样做:
result = bool(python_object)
HowPython对象转换为布尔值,一切取决于它们真值 https://docs.python.org/3/library/stdtypes.html#truth。一般来说,None
、数字0和空容器(空列表、字典、集合、元组、字符串等)都是False
,剩下的就是True
.
每当需要显式布尔值时就可以使用它。假设您正在构建一个对象树,并且您想要包含一个返回的方法True
如果树上有孩子:
class Tree(object):
def __init__(self, children):
self.children = children
def has_children(self):
return bool(self.children)
Now Tree().has_children()
将返回True
when self.children
不为空,False
否则。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)