Boolean value of objects in Python(Python中对象的布尔值)
问题描述
众所周知,Python 对对象有布尔值:如果一个类有一个 __len__
方法,那么 __len__()
碰巧返回 0 的每个实例都会被评估为布尔值 False
(例如,空列表).
As we know, Python has boolean values for objects: If a class has a __len__
method, every instance of it for which __len__()
happens to return 0 will be evaluated as a boolean False
(for example, the empty list).
事实上,如果每个可迭代的空自定义对象出现在布尔表达式中,它都会被评估为 False
.
In fact, every iterable, empty custom object is evaluated as False
if it appears in boolean expression.
现在假设我有一个带有属性bar
的类foo
.我如何定义它的真值,例如,如果 bar % 2 == 0 和 False
否则它将被评估为 True?
Now suppose I have a class foo
with attribute bar
. How can I define its truth value, so that, say, it will be evaluated to True if bar % 2 == 0
and False
otherwise?
例如:
myfoo = foo()
myfoo.bar = 3
def a(foo):
if foo:
print "spam"
else:
print "eggs"
所以,a(myfoo)
应该打印 eggs"
.
推荐答案
在 Python 2 中,使用 __nonzero__
:
请参阅 Python 2 文档以了解 __nonzero__代码>.
class foo(object):
def __nonzero__( self) :
return self.bar % 2 == 0
def a(foo):
if foo:
print "spam"
else:
print "eggs"
def main():
myfoo = foo()
myfoo.bar = 3
a(myfoo)
if __name__ == "__main__":
main()
这篇关于Python中对象的布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Python中对象的布尔值


基础教程推荐
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 筛选NumPy数组 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01