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

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值