Why do function objects evaluate to True in python?

前端 未结 4 1413
后悔当初
后悔当初 2020-12-21 17:36

In python it is valid to make a construction like:

def a(): 
    return 0

if a: 
    print \"Function object was considered True\"
else:  
    print \"Funct         


        
4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-21 18:16

    In the Truth Value Testing that @Magnus Hoff linked to, I found the most instructive statement to be:

    By default, an object is considered true unless its class defines either a _bool_() method that returns False or a _len_() method that returns zero, when called with the object.

    I tried defining my own classes, and it seems like _bool_() takes priority over _len_(), which makes sense:

    class Falsish(object):
        def __init__(self):
            self.val = "False, even though len(self) > 0"
        def __bool__(self):
            return False
        def __len__(self):
            return 2
    
    class StillFalsish(object):
        def __init__(self):
            self.val = "False, even though len(self) > 0"
        def __len__(self):
            return 2
        def __bool__(self):
            return False
    
    class Truish(object):
        def __init__(self):
            self.val = "True, even though len(self) = 0"
        def __bool__(self):
            return True
        def __len__(self):
            return 0
    
    class StillTruish(object):
        def __init__(self):
            self.val = "True, even though len(self) = 0"
        def __len__(self):
            return 0
        def __bool__(self):
            return True
    
    class NowFalsish(object):
        def __init__(self):
            self.val = "False, with no __bool__(), since len(self) = 0"
        def __len__(self):
            return 0
    
    class NowTruish(object):
        def __init__(self):
            self.val = "True, with no __bool__(), since len(self) > 0"
        def __len__(self):
            return 2
    
    class EvenThisIsTruish(object):
        pass
    
    
    mybool1 = Falsish()
    mybool2 = StillFalsish()
    mybool3 = Truish()
    mybool4 = StillTruish()
    mybool5 = NowFalsish()
    mybool6 = NowTruish()
    mybool7 = EvenThisIsTruish()
    if mybool1: print("mybool1 is true")
    if mybool2: print("mybool2 is true")
    if mybool3: print("mybool3 is true")
    if mybool4: print("mybool4 is true")
    if mybool5: print("mybool5 is true")
    if mybool6: print("mybool6 is true")
    if mybool7: print("mybool7 is true")
    

    The output of the above code is:

    mybool3 is true
    mybool4 is true
    mybool6 is true
    mybool7 is true
    

提交回复
热议问题