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
如
整型 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动态类型的学习---引用的理解
- Python3写爬虫(四)多线程实现数据爬取
- 垃圾邮件过滤器 python简单实现
- 下载并遍历 names.txt 文件,输出长度最长的回文人名。
- install and upgrade scrapy
- Scrapy的架构介绍
- Centos6 编译安装Python
- 使用Python生成Excel格式的图片
- 让Python文件也可以当bat文件运行
- [Python]推算数独
- Python中zip()函数用法举例
- Python中map()函数浅析
- Python将excel导入到mysql中
- Python在CAM软件Genesis2000中的应用
- 使用Shiboken为C++和Qt库创建Python绑定
- FREEBASIC 编译可被python调用的dll函数示例
- Python 七步捉虫法