Python __bool__() 方法

Python __bool__() 语法

__bool__() 是 Python 的一个特殊方法(又称 “魔法方法” 或 “双下划线方法”),它定义了当对象被转换为布尔值时(如调用 bool() 函数),是返回 True 还是 False。

__bool__() 方法会在以下场景中自动调用。

语法:

class MyObject:
    def __bool__(self):
        # 根据对象的内部状态返回 True 或 False
        return 布尔值

说明:

__bool__() 方法不接收任何参数,除了 self(实例本身)。

__bool__() 必须返回一个布尔值(True 或 False)。如果返回其他类型,则 Python 会抛出 TypeError 异常。

如果类没有定义 __bool__() 方法,Python 会尝试调用 __len__() 方法。

  • 如果 __len__() 返回 0,则对象被认为是 False。
  • 如果 __len__() 返回非零值,则对象被认为是 True。

如果一个类既没有定义 __bool__() 也没有定义 __len__(),那么它的所有实例默认都被认为是 True。

提示:如果一个类实现了 __bool__() 方法,那么当对该类的实例调用 bool() 函数或在需要布尔值的上下文中使用该实例时,Python 会自动调用这个方法。

Python __bool__() 摘要

属于 Python 魔法方法
使用频率
官方文档 查看
相关方法 __len__()

Python __bool__() 示例

接下来,我们通过几个简单的例子来讲解一下 Python __bool__() 方法是如何使用的。

示例 1:对内置类型使用 bool()

# 数字类型
print(f'bool(0): {bool(0)}')              # False
print(f'bool(1): {bool(1)}')              # True
print(f'bool(-1): {bool(-1)}')            # True
print(f'bool(0.0): {bool(0.0)}')          # False

# 序列和容器类型
print(f"bool(''): {bool('')}")            # False (空字符串)
print(f"bool('lvye'): {bool('lvye')}")    # True (非空字符串)
print(f'bool([]): {bool([])}')            # False (空列表)
print(f'bool([1, 2]): {bool([1, 2])}')    # True (非空列表)
print(f'bool(()): {bool(())}')            # False (空元组)
print(f'bool({{}}): {bool({})}')          # False (空字典)
print(f'bool(set()): {bool(set())}')      # False (空集合)

# NoneType
print(f'bool(None): {bool(None)}')        # False

运行结果如下。

bool(0): False
bool(1): True
bool(-1): True
bool(0.0): False
bool(''): False
bool('lvye'): True
bool([]): False
bool([1, 2]): True
bool(()): False
bool({}): False
bool(set()): False
bool(None): False

分析:

对于内置类型,Python 有明确的真值规则:0、空序列(如空字符串、空列表、空元组、空字典、空集合)、None 和 False 等都会被认为是假值(False),而其他所有值(非零数字、非空序列、True 本身等)则会被认为是真值(True)。

示例 2:自定义类实现 __bool__() 方法

class Switch:
    def __init__(self, is_on):
        self.is_on = is_on

    def __bool__(self):
        # 根据 is_on 属性返回布尔值
        return self.is_on

# 创建 Switch 实例
switch_on = Switch(True)
switch_off = Switch(False)

if switch_on:
    print('Switch is ON!')
else:
    print('Switch is OFF!')

if switch_off:
    print('Switch is ON!')
else:
    print('Switch is OFF!')

# 直接使用 bool() 函数
print(bool(switch_on))
print(bool(switch_off))

运行结果如下。

Switch is ON!
Switch is OFF!
True
False

分析:

在 Switch 类中,我们手动实现 __bool__() 方法。该方法会使得其实例的布尔值由其内部的 is_on 属性决定。

当 switch_on 和 switch_off 在 if 语句或 bool() 函数中使用时,Python 会自动调用 __bool__() 方法来获取其布尔值。

示例 3:没有 __bool__() 但有 __len__()

class MyContainer:
    def __init__(self, elements):
        self.elements = list(elements)

    def __len__(self):
        # 定义长度,同时影响布尔值
        return len(self.elements)

# 创建实例
containerA = MyContainer([])
containerB = MyContainer(['a', 'b', 'c'])

if containerA:
    print('containerA is True')
else:
    print('containerA is False')

if containerB:
    print('containerB is True')
else:
    print('containerB is False')

# 直接使用 bool() 函数
print(bool(containerA))
print(bool(containerB))

运行结果如下。

containerA is False
containerB is True
False
True

分析:

如果一个类没有定义 __bool__() 方法,但定义了 __len__() 方法,Python 会根据 __len__() 的返回值来确定对象的布尔值:len(obj) == 0 被认为是 False,否则为 True。

示例 4:既无 __bool__() 也无 __len__()

class MyObject:
    def __init__(self, name):
        self.name = name
    # 没有 __bool__() 也 没有 __len__()

# 创建实例
obj1 = MyObject('实例1')
obj2 = MyObject('实例2')

if obj1:
    print(f'{obj1.name} is True')
else:
    print(f'{obj1.name} is False')

if obj2:
    print(f'{obj2.name} is True')
else:
    print(f'{obj2.name} is False')

# 直接使用 bool() 函数
print(bool(obj1))
print(bool(obj2))

运行结果如下。

实例1 is True
实例2 is True
True
True

分析:

如果一个类既没有实现 __bool__() 也没有实现 __len__() 方法,那么它的所有实例在布尔上下文中都默认被认为是 True。

上一篇: __hash__()

下一篇: __call__()

给站长反馈

绿叶网正在不断完善中,小伙伴们如果发现任何问题,还望多多给站长反馈,谢谢!

邮箱:lvyenet@vip.qq.com

「绿叶网」服务号
绿叶网服务号放大
关注服务号,微信也能看教程。
绿叶网服务号