Why does `if None.__eq__(“a”)` seem to evaluate to True (but not quite)?

前端 未结 4 1639
轮回少年
轮回少年 2020-12-07 12:04

If you execute the following statement in Python 3.7, it will (from my testing) print b:

if None.__eq__(\"a\"):
    print(\"b\")
4条回答
  •  [愿得一人]
    2020-12-07 12:23

    As you already figured None.__eq__("a") evaluates to NotImplemented however if you try something like

    if NotImplemented:
        print("Yes")
    else:
        print("No")
    

    the result is

    yes

    this mean that the truth value of NotImplemented true

    Therefor the outcome of the question is obvious:

    None.__eq__(something) yields NotImplemented

    And bool(NotImplemented) evaluates to True

    So if None.__eq__("a") is always True

提交回复
热议问题