为了账号安全,请及时绑定邮箱和手机立即绑定

isinstance(False, int) 返回 True

isinstance(False, int) 返回 True

桃花长相依 2022-09-06 17:51:17
我想确定变量是否为整数,因此我使用以下代码:if isinstance(var, int):     do_something()但是当 执行时,函数被执行。var = Falsedo_something当 时,函数正常工作。var = Noneisinstance()
查看完整描述

3 回答

?
慕村225694

TA贡献1880条经验 获得超4个赞

因为 是 的子类。

您可以在以下位置找到它boolintbuiltins.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.

    """

所以也.

是 当 的类型是 的派生类时。issubclass(bool, int)Trueisinstance(x, y)Truexy


查看完整回答
反对 回复 2022-09-06
?
达令说

TA贡献1821条经验 获得超6个赞

在布尔值中被定义为整数的子类。Python3

该均值等价于 as 等价于True1False0

您可以在此处找到更多详细信息。该链接的完全相同的解释是:

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


查看完整回答
反对 回复 2022-09-06
?
HUH函数

TA贡献1836条经验 获得超4个赞

Python 将 和 视为 。现在你可以在这里做的是:True1False0


try:

    var = int(string(False))

except ValueError:

    print("Invalid Integer")


查看完整回答
反对 回复 2022-09-06
  • 3 回答
  • 0 关注
  • 163 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信