Assign class boolean value in Python(在 Python 中分配类布尔值)
问题描述
Python 中的 If 语句允许您执行以下操作:
If statements in Python allow you to do something like:
if not x:
print "X is false."
如果您使用的是空列表、空字典、None、0 等,则此方法有效,但如果您有自己的自定义类怎么办?你能为那个类分配一个 false 值,以便在相同的条件样式中,它会返回 false 吗?
This works if you're using an empty list, an empty dictionary, None, 0, etc, but what if you have your own custom class? Can you assign a false value for that class so that in the same style of conditional, it will return false?
推荐答案
你需要实现 __nonzero__
方法.这应该返回 True 或 False 以确定真值:
You need to implement the __nonzero__
method on your class. This should return True or False to determine the truth value:
class MyClass(object):
def __init__(self, val):
self.val = val
def __nonzero__(self):
return self.val != 0 #This is an example, you can use any condition
x = MyClass(0)
if not x:
print 'x is false'
如果未定义 __nonzero__
,则实现将调用 __len__
并且如果实例返回非零值,则该实例将被视为 True.如果 __len__
也没有定义,所有实例都将被视为 True.
If __nonzero__
has not been defined, the implementation will call __len__
and the instance will be considered True if it returned a nonzero value. If __len__
hasn't been defined either, all instances will be considered True.
在 Python 3 中,__bool__使用 code> 代替
__nonzero__
.
In Python 3, __bool__
is used instead of __nonzero__
.
这篇关于在 Python 中分配类布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Python 中分配类布尔值


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