自定义对象与bool之间的转换

来源:互联网 发布:龚琳娜 知乎 编辑:程序博客网 时间:2024/05/20 21:20
"""python中的所有数据类型都能转bool对应关系:0  空序列 字典 None -》Falseelse ->True但是对于自定义对象来说:这种转换受到内置函数__bool____len__返回值的影响其中__bool__影响优先级高于__len__"""class Test():    passprint(bool(Test()))class Test1():    def __len__(self):        return 0print(bool(Test1()))class Test2():    def __bool__(self):        return Falseprint(bool(Test2()))class Test3():    def __bool__(self):        return True    def __len__(self):        return 0print(bool(Test3()))--------------------------C:\Python\Python36\python.exe D:/IdeaProjects/python_basic/extend/learn_boo.pyTrueFalseFalseTrueProcess finished with exit code 0
原创粉丝点击