您的位置:首页 > 编程语言 > Python开发

python 类中的__nozero__ ,__len__ 重写,可以定义对象的布尔值是True or False

2016-05-05 22:35 701 查看
Python中,每个对象都具有True和False,空对象、值为零的任何数字或者NULL对象None的布尔值都是False。



整型  0 

长整型 0L

浮点数 0.0

空列表 []

空元组()

空字典()

空字符串 ""

None

复数0.0+0.0j 

对于一个自定义的类,可以通过重写__nozero__(), __len__()函数来说明一个类对象是否为False。 如果__nozero__()或者__len__() 返回值为零,则对象为False, 否则为True。

例1:

class test_nozero(object):

    def __init__(self):

        print "test_nozero init"

    def __nozero__(self):

         return 1

    #def __len__(self):

    #    return 0

    

if __name__ == '__main__':

    a=test_nozero()

    #print a

    if   a :

        print "not zero"

    else:

        print "zero"

执行结果如下:

test_nozero init

not zero

例二:

class test_nozero(object):

    def __init__(self):

        print "test_nozero init"

    def __nozero__(self):

         return 0

    #def __len__(self):

    #    return 0

    

if __name__ == '__main__':

    a=test_nozero()

    #print a

    if   a :

        print "not zero"

    else:

        print "zero"

执行结果如下:

test_nozero init

zero
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python __nozero__