isinstance(False,int)返回True

2024-03-29 05:10:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我想确定变量是否为整数,因此使用以下代码:

if isinstance(var, int):
    do_something()

但是当var = False时,执行do_something函数

var = None时,isinstance()函数正常工作


Tags: 函数代码nonefalseifvar整数do
3条回答

Python将True视为1,将False视为0。现在,您可以在这里执行以下操作:

try:
    var = int(string(False))
except ValueError:
    print("Invalid Integer")

Python3中,布尔定义为整数的子类

这意味着True等同于1,其中asFalse等同于0

您可以在here中找到更多详细信息。从该链接中得出的完全相同的解释是:

There are three distinct numeric types: integers, floating point numbers, and complex numbers. In addition, Booleans are a subtype of integers

因为boolint的一个子类。
你可以在builtins.py中找到它

class bool(int):
    """
    bool(x) -> bool

    Returns True when the argument x is true, False otherwise.
    The builtins True and False are the only two instances of the class bool.
    The class bool is a subclass of the class int, and cannot be subclassed.
    """

所以{}也{}。
^当x的类型是y类型的派生类时,{}是True

相关问题 更多 >