python重写__bool__和__len__作用

  1. boollen__和bool相关,在if中会被调用,优先调用__bool,没有就调用__len__

class Test:
    def __bool__(self):
        print('__bool__')
        return False

    def __len__(self):
        print('__len__')
        return True


t = Test()

if t:         # 调用方式1
    print(t)

bool(t)       # 调用方式2


# 结果
'''
__bool__
__bool__
'''
posted @ 2021-04-15 15:51  该显示昵称已被使用了  阅读(118)  评论(0编辑  收藏  举报