在 Python 中分配类布尔值 [英] Assign class boolean value in Python

查看:26
本文介绍了在 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__ 代替 __nonzero__.

In Python 3, __bool__ is used instead of __nonzero__.

这篇关于在 Python 中分配类布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆