为什么要隐式检查Python中的空度? [英] Why implicitly check for emptiness in Python?
问题描述
Python的禅宗说显式比隐式好.
The Zen of Python says that explicit is better than implicit.
但是检查集合c是否为空的Python方式是:
Yet the Pythonic way of checking a collection c for emptiness is:
if not c:
# ...
,然后检查集合是否不为空
and checking if a collection is not empty is done like:
if c:
# ...
同上用于任何可能具有零"或空"(元组,整数,字符串,无等)的
ditto for anything that can have "zeroness" or "emptiness" (tuples, integers, strings, None, etc)
这是什么目的?如果我不这样做,我的代码会不会出错?还是它可以启用更多用例(即某种多态性),因为人们可以覆盖这些布尔强制?
What is the purpose of this? Will my code be buggier if I don't do this? Or does it enable more use cases (i.e: some kind of polymorphism) since people can override these boolean coercions?
推荐答案
此最佳做法并非没有道理.
This best practice is not without reason.
在测试 if object:
时,您基本上是在调用对象 __ bool __
方法,该方法可以根据对象行为进行覆盖和实现.
When testing if object:
you are basically calling the objects __bool__
method, which can be overridden and implemented according to object behavior.
例如,集合上的 __ bool __
方法(Python 2中为 __ nonzero __
)将根据集合是否为空返回布尔值.
For example, the __bool__
method on collections (__nonzero__
in Python 2) will return a boolean value based on whether the collection is empty or not.
(参考: http://docs.python.org/reference/datamodel.html )
这篇关于为什么要隐式检查Python中的空度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!