python使用isinstance比较boolean和int [英] python comparing boolean and int using isinstance

查看:246
本文介绍了python使用isinstance比较boolean和int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以解释为什么 isinstance()在下列情况下返回True?在编写代码时我期望False。

Can someone give me an explanation why isinstance() returns True in the following case? I expected False, when writing the code.

print isinstance(True, (float, int))
True

我的猜测是它的python的内部子类,零和一个浮点数或者int - 都评估当用作布尔值时,但不知道确切的原因。

My guess would be that its python's internal subclassing, as zero and one - wheter float or int - both evaluate when used as boolean, but don't know the exact reason.

解决这种情况的最pythonic方法是什么?我可以使用 type(),但在大多数情况下,这被认为是pythonic。

What would be the most pythonic way to solve a such a situation? I could use type() but in most cases this is considered less pythonic.

推荐答案

由于历史原因, bool int 的子类,所以 True int 的实例。 (最初,Python没有bool类型,返回真值的东西返回1或0. 当他们添加 bool 时,为了向后兼容,True和False必须尽可能为1和0的替换,因此是子类化。)

For historic reasons, bool is a subclass of int, so True is an instance of int. (Originally, Python had no bool type, and things that returned truth values returned 1 or 0. When they added bool, True and False had to be drop-in replacements for 1 and 0 as much as possible for backward compatibility, hence the subclassing.)

解决这个问题的正确方法取决于你认为的问题。

The correct way to "solve" this depends on exactly what you consider the problem to be.


  • 如果你想 True 停止成为 int ,那么太糟糕了。这不会发生。

  • 如果您想检测布尔值并以不同于其他整数的方式处理它们,您可以这样做:

  • If you want True to stop being an int, well, too bad. That's not going to happen.
  • If you want to detect booleans and handle them differently from other ints, you can do that:

if isinstance(whatever, bool):
    # special handling
elif isinstance(whatever, (float, int)):
    # other handling


  • 如果要检测特定类正好的对象float int ,拒绝子类,你可以这样做:

  • If you want to detect objects whose specific class is exactly float or int, rejecting subclasses, you can do that:

    if type(whatever) in (float, int):
        # Do stuff.
    


  • 如果你想检测所有的浮点数和整数,你已经这样做了。

  • 这篇关于python使用isinstance比较boolean和int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆