美文网首页
python 对象 __bool__ 和 __len__函数

python 对象 __bool__ 和 __len__函数

作者: 楼下小黑666 | 来源:发表于2018-08-20 22:03 被阅读0次

    我们知道在python中一切皆对象,Python中的None,他也属于NoneType这个类型。
    在python中,对象可以当做bool值判断

    def test():
      pass
    print(bool(test))  #返回true
    
    

    在python3中两个内置函数__len __ 和__bool __决定了一个对象的bool值,优先选择__bool __判断,没有__bool __函数则用__len __

    
    class Test1():
        pass
    
    class Test2():
        def __bool__(self):
            return False
        
        def __len__(self):
            return 0
    
    class Test3():
        # def __bool__(self):
        #     return False
        
        def __len__(self):
            return 0
    
    test1 = Test1()
    test2 = Test2()  
    test3 = Test3()      
    print(bool(test1)) # 没有定义bool和len对象,默认为True
    print(bool(test2)) # bool函数决定布尔值,返回False
    print(bool(test3)) # 没有bool函数,则由len函数决定bool值,返回False
    

    相关文章

      网友评论

          本文标题:python 对象 __bool__ 和 __len__函数

          本文链接:https://www.haomeiwen.com/subject/yksriftx.html