检查变量是否为整数 [英] Checking whether a variable is an integer or not

查看:59
本文介绍了检查变量是否为整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何检查变量是否为整数?

How do I check whether a variable is an integer?

推荐答案

如果需要这样做,请

isinstance(<var>, int)

除非您使用的是Python 2.x,否则您需要

unless you are in Python 2.x in which case you want

isinstance(<var>, (int, long))

请勿使用 type .在Python中,这几乎从来都不是正确的答案,因为它阻止了多态性的所有灵活性.例如,如果您将 int 子类化,则新类应注册为 int ,而 type 不会:

Do not use type. It is almost never the right answer in Python, since it blocks all the flexibility of polymorphism. For instance, if you subclass int, your new class should register as an int, which type will not do:

class Spam(int): pass
x = Spam(0)
type(x) == int # False
isinstance(x, int) # True

这符合Python强大的多态性:您应该允许行为类似于 int 的任何对象,而不是强制其成为一个对象.

This adheres to Python's strong polymorphism: you should allow any object that behaves like an int, instead of mandating that it be one.

不过,经典的Python心态是,要求宽恕比获得许可要容易.换句话说,不要检查 x 是否为整数;假设它是,如果不是,则捕获异常结果:

The classical Python mentality, though, is that it's easier to ask forgiveness than permission. In other words, don't check whether x is an integer; assume that it is and catch the exception results if it isn't:

try:
    x += 1
except TypeError:
    ...

使用抽象基类逐渐取代了这种思想.您可以通过使对象继承自特殊构造的类来确切地注册对象应具有的属性(加,乘,乘,加).那将是最好的解决方案,因为它将允许完全具有必需和足够属性的那些对象,但是您将必须阅读有关如何使用它的文档.

This mentality is slowly being overtaken by the use of abstract base classes, which let you register exactly what properties your object should have (adding? multiplying? doubling?) by making it inherit from a specially-constructed class. That would be the best solution, since it will permit exactly those objects with the necessary and sufficient attributes, but you will have to read the docs on how to use it.

这篇关于检查变量是否为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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