摘要:In Python, we often need to determine whether an object is "empty" or "true", for example:
分享兴趣,传播快乐,
增长见闻,留下美好!
亲爱的您,这里是LearningYard新学苑。
今天小编为大家带来文章
“刘心向学(39):len 与 bool深入理解对象的“真值”与长度判断”
Share interest, spread happiness,
Increase knowledge, leave a beautiful!
Dear, this is LearningYard Academy.
Today, the editor brings you an article.
“Liu Xinxiangxue (38): __enter__ vs __exit__: Understanding Context Managers in Python”
在 Python 中,我们经常需要判断一个对象是否“为空”或“为真”,比如:
In Python, we often need to determine whether an object is "empty" or "true", for example:
Python深色版本if my_list:print("列表不为空")或者获取一个对象的长度:
Or get the length of an object:
Python深色版本len(my_string)这些看似简单的操作背后,其实是 Python 魔法方法在起作用。其中,__len__ 和 __bool__ 是控制对象“长度”和“布尔值”的两个核心魔法方法。
Behind these seemingly simple operations are Python's magic methods. Among them, __len__ and __bool__ are the two core magic methods that control an object's "length" and "truth value".
本文将带你深入理解 __len__ 与 __bool__ 的工作原理、调用优先级、设计原则,并通过多个实际示例展示如何在自定义类中合理实现它们,从而让我们的对象更符合 Python 的“惯用法”(Pythonic)。
This article will guide you through the working principles, call priority, and design principles of __len__ and __bool__, and demonstrate through multiple practical examples how to properly implement them in custom classes, making our objects more Pythonic.
在 Python 中,每个对象都可以被用于布尔上下文(如 if、while 等),也可以被查询长度(通过 len 函数)。这种行为由两个魔法方法控制:
In Python, every object can be used in a boolean context (such as if, while, etc.) and can have its length queried (via the len function). This behavior is controlled by two magic methods:
len(obj) 实际上是调用 obj.__len__。
len(obj) is actually calling obj.__len__.
Python深色版本classMyList:def__init__(self, items): self.items = itemsdef__len__(self):returnlen(self.items)my_list = MyList([1, 2, 3])print(len(my_list)) # 输出: 3必须返回一个 非负整数(int)。
Must return a non-negative integer (int).
如果返回负数或非整数类型,会引发 TypeError。
Must return a non-negative integer (int).
Python深色版本def__len__(self):return -1# ❌ 错误:长度不能为负bool(obj) 或在布尔上下文中使用对象时,会调用 obj.__bool__。
bool(obj) or using an object in a boolean context calls obj.__bool__
Python深色版本classPerson:def__init__(self, name): self.name = namedef__bool__(self):returnbool(self.name) # 名字非空则为 Truep1 = Person("Alice")p2 = Person("")print(bool(p1)) # Trueprint(bool(p2)) # Falseif p1:print("Person has a name") # 会执行如果类没有定义 __bool__ 方法,Python 会尝试调用 __len__:
If the class does not define a __bool__ method, Python will attempt to call __len__:
如果 __len__ 返回 0 → 对象为 False
否则 → 对象为 True
If __len__ returns 0 → the object is False
Otherwise → the object is True
如果两者都没有定义,则对象始终为 True。
Python 在判断对象真假时的优先级如下:
The priority when Python evaluates the truthiness of an object is as follows:
示例:优先级演示
Example: Priority Demonstration
Python深色版本classContainer:def__len__(self):print("__len__ called")return0def__bool__(self):print("__bool__ called")returnTruec = Containerprint(bool(c)) # 输出: __bool__ called \n True即使 __len__ 返回 0,但由于 __bool__ 存在且返回 True,最终结果仍为 True。
Python深色版本classStack:def__init__(self): self._items = defpush(self, item): self._items.append(item)defpop(self):return self._items.popdef__len__(self):returnlen(self._items)def__bool__(self):returnlen(self._items) > 0s = Stackprint(len(s)) # 0print(bool(s)) # Falses.push(1)print(bool(s)) # TrueState-Evaluation Object
Python深色版本classResponse:def__init__(self, data=None, success=False): self.data = data self.success = successdef__bool__(self):return self.success and (self.data isnotNone)resp = Response(data={"user": "Alice"}, success=True)if resp:print("请求成功并有数据") # 会执行掌握它们的调用机制和设计原则,是写出优雅、健壮 Python 代码的重要一步。
Mastering their call mechanisms and design principles is an essential step toward writing elegant and robust Python code.
无论你是在构建数据结构、封装 API 响应,还是设计领域模型,__len__ 与 __bool__ 都是你值得深入理解并善用的工具。
Whether you're building data structures, wrapping API responses, or designing domain models, __len__ and __bool__ are tools worth deeply understanding and skillfully using.
今天的分享就到这里了。
如果您对文章有独特的想法,
欢迎给我们留言,
让我们相约明天。
祝您今天过得开心快乐!
That's all for today's sharing.
If you have a unique idea about the article,
please leave us a message,
and let us meet tomorrow.
I wish you a nice day!
参考资料:通义千问
参考文献:Beazley, D., & Jones, B. K. (2019). Python Cookbook (3rd ed.). O'Reilly Media.
Hettinger, R. (2019). Transforming Code into Beautiful, Idiomatic Python. PyCon US.
本文由LearningYard新学苑整理发出,如有侵权请在后台留言沟通!
LearningYard新学苑
文字:song
排版:song
审核|qiu
来源:LearningYard学苑