What is Truthy and Falsy? How is it different from True and False?

前端 未结 6 1547
广开言路
广开言路 2020-11-21 04:16

I just learned there are truthy and falsy values in python which are different from the normal True and False.

6条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-21 05:11

    Python determines the truthiness by applying bool() to the type, which returns True or False which is used in an expression like if or while.

    Here is an example for a custom class Vector2dand it's instance returning False when the magnitude (lenght of a vector) is 0, otherwise True.

    import math
    class Vector2d(object):
        def __init__(self, x, y):
            self.x = float(x)
            self.y = float(y)
    
        def __abs__(self):
            return math.hypot(self.x, self.y)
    
        def __bool__(self):
            return bool(abs(self))
    
    a = Vector2d(0,0)
    print(bool(a))        #False
    b = Vector2d(10,0)    
    print(bool(b))        #True
    

    Note: If we wouldn't have defined __bool__ it would always return True, as instances of a user-defined class are considered truthy by default.

    Example from the book: "Fluent in Python, clear, concise and effective programming"

提交回复
热议问题