如何在Python中对变量进行类型检查? [英] How can I type-check variables in Python?

查看:145
本文介绍了如何在Python中对变量进行类型检查?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Python函数,该函数带有一个数字参数,必须是整数,以便其正确运行.在Python中进行验证的首选方式是什么?

I have a Python function that takes a numeric argument that must be an integer in order for it behave correctly. What is the preferred way of verifying this in Python?

我的第一反应是做这样的事情:

My first reaction is to do something like this:

def isInteger(n):
    return int(n) == n

但是我不禁会认为这是1)昂贵的2)丑陋的和3)受到机器epsilon的怜悯之情的.

But I can't help thinking that this is 1) expensive 2) ugly and 3) subject to the tender mercies of machine epsilon.

Python是否提供任何本机的类型检查变量方法?还是认为这违反了该语言的动态类型设计?

Does Python provide any native means of type checking variables? Or is this considered to be a violation of the language's dynamically typed design?

由于许多人提出了疑问-有问题的应用程序可使用IPv4前缀,从纯文本文件中获取数据.如果将任何输入解析为浮点数,则该记录应被视为格式错误并被忽略.

since a number of people have asked - the application in question works with IPv4 prefixes, sourcing data from flat text files. If any input is parsed into a float, that record should be viewed as malformed and ignored.

推荐答案

isinstance(n, int)

如果您需要知道它是否绝对是实际的int而不是int的子类(通常不需要这样做):

If you need to know whether it's definitely an actual int and not a subclass of int (generally you shouldn't need to do this):

type(n) is int

此:

return int(n) == n

并不是一个好主意,因为交叉类型比较可能是正确的-尤其是int(3.0)==3.0

isn't such a good idea, as cross-type comparisons can be true - notably int(3.0)==3.0

这篇关于如何在Python中对变量进行类型检查?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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