You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何证明Python中的布尔值(boolean)是不可变对象?

How to Prove Booleans Are Immutable in Python

Great question! Let's walk through concrete, easy-to-follow ways to demonstrate that boolean objects (True/False) are immutable in Python. First, a quick recap: immutable objects are those whose state (value) can’t be modified after creation—any "change" you try to make actually creates a brand-new object instead of altering the original.

1. Track Object IDs to See "Modifications" Create New Objects

Every Python object has a unique identifier you can check with the id() function. For immutable types, reassigning a variable to a different value doesn’t tweak the original object—it just makes the variable point to a new one.

Try running this code:

# Assign a boolean to a variable
my_bool = True
print(f"ID of initial True: {id(my_bool)}")

# "Change" the variable's value
my_bool = False
print(f"ID of new False: {id(my_bool)}")

You’ll see two completely different IDs. This proves we didn’t modify the original True object—we just redirected my_bool to reference the separate False singleton instead.

2. Attempt to Modify Boolean Attributes (It Will Fail)

Immutable objects block any attempt to add or modify their attributes after creation. Since bool inherits from int (another immutable type), trying to alter its properties throws a clear error:

test_bool = True
test_bool.custom_attr = "hello"  # This line will crash!

You’ll get an error message like:

AttributeError: 'bool' object has no attribute 'custom_attr'

This is a dead giveaway of immutability—Python actively prevents you from changing the object’s internal state or adding new properties.

3. Verify Booleans Are Singletons

Python only creates one instance of True and one instance of False across the entire interpreter. Every variable set to True points to the exact same object:

a = True
b = True
c = 1 == 1  # Evaluates to True

print(a is b)  # Output: True (same underlying object)
print(a is c)  # Output: True (also the same object)

If booleans were mutable, changing one True variable’s value would affect all others—but since you can’t modify the underlying True object itself, this is impossible. Any "change" just redirects the variable to a different singleton.


内容的提问来源于stack exchange,提问作者newbieeyo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:10:23