在 Python 中分配类布尔值

2022-01-20 00:00:00 python class conditional-statements

问题描述

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__ 代替 __nonzero__.

In Python 3, __bool__ is used instead of __nonzero__.

相关文章