如何检查我的 python 对象是否为数字?

2023-07-04Python开发问题
4

本文介绍了如何检查我的 python 对象是否为数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

在 Java 中,数字类型都来自 Number,所以我会使用

In Java the numeric types all descend from Number so I would use

(x instanceof Number).

python 等价物是什么?

What is the python equivalent?

推荐答案

测试你的变量是否是 numbers.Number:

Test if your variable is an instance of numbers.Number:

>>> import numbers
>>> import decimal
>>> [isinstance(x, numbers.Number) for x in (0, 0.0, 0j, decimal.Decimal(0))]
[True, True, True, True]

这使用 ABCs 并且适用于所有内置在类似数字的类中,也适用于所有第三方类,如果它们是值得的(注册为 Number ABC 的子类).

This uses ABCs and will work for all built-in number-like classes, and also for all third-party classes if they are worth their salt (registered as subclasses of the Number ABC).

但是,在许多情况下,您不必担心手动检查类型 - Python 是 duck typed 并且混合一些兼容的类型通常是可行的,但是当某些操作没有意义时(4 - 1")会发出错误消息,因此很少需要手动检查.这只是一个奖金.您可以在完成模块时添加它,以避免在实现细节上纠缠他人.

However, in many cases you shouldn't worry about checking types manually - Python is duck typed and mixing somewhat compatible types usually works, yet it will barf an error message when some operation doesn't make sense (4 - "1"), so manually checking this is rarely really needed. It's just a bonus. You can add it when finishing a module to avoid pestering others with implementation details.

这适用于从 Python 2.6 开始.在旧版本上,您几乎只能检查一些硬编码类型.

This works starting with Python 2.6. On older versions you're pretty much limited to checking for a few hardcoded types.

这篇关于如何检查我的 python 对象是否为数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

在xarray中按单个维度的多个坐标分组
groupby multiple coords along a single dimension in xarray(在xarray中按单个维度的多个坐标分组)...
2024-08-22 Python开发问题
15

Pandas中的GROUP BY AND SUM不丢失列
Group by and Sum in Pandas without losing columns(Pandas中的GROUP BY AND SUM不丢失列)...
2024-08-22 Python开发问题
17

pandas 有从特定日期开始的按月分组的方式吗?
Is there a way of group by month in Pandas starting at specific day number?( pandas 有从特定日期开始的按月分组的方式吗?)...
2024-08-22 Python开发问题
10

GROUP BY+新列+基于条件的前一行抓取值
Group by + New Column + Grab value former row based on conditionals(GROUP BY+新列+基于条件的前一行抓取值)...
2024-08-22 Python开发问题
18

PANDA中的Groupby算法和插值算法
Groupby and interpolate in Pandas(PANDA中的Groupby算法和插值算法)...
2024-08-22 Python开发问题
11

PANAS-基于列对行进行分组,并将NaN替换为非空值
Pandas - Group Rows based on a column and replace NaN with non-null values(PANAS-基于列对行进行分组,并将NaN替换为非空值)...
2024-08-22 Python开发问题
10