定义" boolness"在python一类 [英] defining "boolness" of a class in python

查看:136
本文介绍了定义" 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__

或扩大富的原始定义为包括:

or expand the original definition of Foo to include:

__nonzero__ = __bool__

您当然可以反向定义它们太,其中方法名称为 __非零__ 键,将其分配给 __布尔__ ,但我觉得这个名字 __非零__ 只是一个对象的Python的跨pretation原C-ishness作为truthy或falsy基于其零等值的遗产。只需添加上述声明和你的code将与Python 2.x的工作,当你升级到Python 3.x中会自动工作(最终你的下降分配到 __ __非零)。

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天全站免登陆