定义“boolness"python中的一个类 [英] Defining "boolness" of a class in python

查看:21
本文介绍了定义“boolness"python中的一个类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这不像人们天真的预期的那样工作?

Why doesn't this work as one may have naively expected?

class Foo(object):
    def __init__(self):
        self.bar = 3
    def __bool__(self):
        return self.bar > 10

foo = Foo()

if foo:
    print 'x'
else:
    print 'y'

(输出为x)

推荐答案

对于 Python 2-3 兼容性,只需将其添加到您的示例中:

For Python 2-3 compatibility, just add this to your example:

Foo.__nonzero__ = Foo.__bool__

或扩展 Foo 的原始定义以包括:

or expand the original definition of Foo to include:

__nonzero__ = __bool__

你当然也可以反过来定义它们,其中方法名称是 __nonzero__ 并将它分配给 __bool__,但我认为名称 __nonzero__ 只是 Python 根据对象与零的等价性将对象解释为真或假的原始 C-ishness 的遗产.只需添加上面的语句,您的代码将适用于 Python 2.x,并且会在您升级到 Python 3.x 时自动运行(最终您放弃对 __nonzero__ 的赋值).

You could of course define them in reverse too, where the method name is __nonzero__ and you assign it to __bool__, but I think the name __nonzero__ is just a legacy of the original C-ishness of Python's interpretation of objects as truthy or falsy based on their equivalence with zero. Just add the statement above and your code will work with Python 2.x, and will automatically work when you upgrade to Python 3.x (and eventually you an drop the assignment to __nonzero__).

这篇关于定义“boolness"python中的一个类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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