Python中对象布尔值的计算

每个对象都可以在布尔上下中被计算,如ifwhile语句。下面示例将演示对象是TrueFalse的规则。

没有__bool__()和__len__()的对象为True

class Foo():
    pass

foo = Foo()
if foo:
    print("It's true")
else:
    print("well, it's false")

bool()决定对象的正确性

如果对象有__bool__方法,__bool__()决定对象的正确性。需要注意的是,Python期望__bool__()返回一个布尔值,否则会抛出异常TypeError

class Foo:
    def __init__(self, cnt_true):
        self.cnt_true = cnt_true

    def __bool__(self):
        print('__bool__: cnt_true = ' + str(self.cnt_true))

        self.cnt_true -= 1
        return self.cnt_true >= 0


foo = Foo(4)
while foo:
    print('Still in loop')
print("Loop exited")

# __bool__: cnt_true = 4
# Still in loop
# __bool__: cnt_true = 3
# Still in loop
# __bool__: cnt_true = 2
# Still in loop
# __bool__: cnt_true = 1
# Still in loop
# __bool__: cnt_true = 0
# Loop exited

如果没有__bool__(),则会通过__len__()判断

如果对象没有__bool__()方法,而有__len__()方法,__len__()的返回值决定了对象的正确性。如果返回值为0,对象就是False,否则就是True.需要注意的是,Python期望__len__()返回一个整型。

class Foo:
    def __init__(self, cnt_true):
        self.cnt_true = cnt_true

    def __len__(self):
        print("__len__: cnt_true = " + str(self.cnt_true))
        self.cnt_true -= 1
        return self.cnt_true


foo = Foo(4)
while foo:
    print('Still in loop')
print("Loop exited")

# __len__: cnt_true = 4
# Still in loop
# __len__: cnt_true = 3
# Still in loop
# __len__: cnt_true = 2
# Still in loop
# __len__: cnt_true = 1
# Loop exited

bool()的优先级高于__len__()

class Foo:
    def __init__(self, cnt_true):
        self.cnt_true = cnt_true

    def __bool__(self):
        print('__bool__: cnt_true = ' + str(self.cnt_true))

        self.cnt_true -= 1
        return self.cnt_true >= 0

    def __len__(self):
        print("__len__: cnt_true = " + str(self.cnt_true))
        self.cnt_true -= 1
        return self.cnt_true


foo = Foo(4)
while foo:
    print('Still in loop')
print("Loop exited")

# __bool__: cnt_true = 4
# Still in loop
# __bool__: cnt_true = 3
# Still in loop
# __bool__: cnt_true = 2
# Still in loop
# __bool__: cnt_true = 1
# Still in loop
# __bool__: cnt_true = 0
# Loop exited
posted @ 2020-10-30 15:45  yw_sun  阅读(491)  评论(0编辑  收藏  举报