bool()在Python中的实际应用是什么? [英] What is the practical application of bool() in Python?

查看:157
本文介绍了bool()在Python中的实际应用是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

何时将其用于日常编码中?我正在使用本教程来学习Python. 此处(页面中部)已对我所指的内容进行了说明,但我无法得到它.我了解使用True和False的原理,但我不知道何时(或确实)在编写代码时实际上在实践中使用bool()函数.如果您在代码中提供日常实用的bool()示例,将会对我有帮助.

When it is being used in everyday coding? I am learning Python using this tutorial. What am I referring to is described here (middle of the page), but I can't get it. I understand the principles of using True and False, but I don't get when (or do) we actually use the bool() function in practice while writing our code. It would help me if you give the everyday, practical example of bool() in code.

推荐答案

它使您可以将任何Python值转换为布尔值.

It lets you convert any Python value to a boolean value.

有时您想存储TrueFalse取决于另一个Python对象.代替:

Sometimes you want to store either True or False depending on another Python object. Instead of:

if python_object:
    result = True
else:
    result = False

您只需这样做:

result = bool(python_object)

如何将Python对象转换为布尔值,全部取决于其真实值.一般来说,None,数字0和空容器(空列表,字典,集合,元组,字符串等)都是False,其余的是True.

How Python objects are converted to a boolean value, all depends on their truth value. Generally speaking, None, numeric 0 and empty containers (empty list, dictionary, set, tuple, string, etc.) are all False, the rest is True.

在需要显式布尔值时使用它.假设您正在构建对象树,并且要包含一个方法,如果树中有子对象,则该方法返回True:

You use it whenever you need an explicit boolean value. Say you are building an object tree, and you want to include a method that returns True if there are children in the tree:

class Tree(object):
    def __init__(self, children):
        self.children

    def has_children(self):
        return bool(self.children)

现在,当self.children不为空时,Tree().has_children()将返回True,否则为False.

Now Tree().has_children() will return True when self.children is not empty, False otherwise.

这篇关于bool()在Python中的实际应用是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆