检查对象是否为数字的最pythonic方法是什么? [英] What is the most pythonic way to check if an object is a number?

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

问题描述

给定一个任意的python对象,确定它是否是数字的最佳方法是什么?这里is被定义为在某些情况下就像一个数字.

例如,假设您正在编写一个向量类.如果给定另一个向量,您希望找到点积.如果给定一个标量,您希望缩放整个向量.

检查是否有 intfloatlongbool 很烦人,并且不覆盖用户- 定义的对象可能像数字一样.但是,例如,检查 __mul__ 还不够好,因为我刚刚描述的向量类将定义 __mul__,但它不会是我所描述的那种数字想要.

解决方案

使用 Number 来自 numbers 用于测试 isinstance(n, Number) 的模块(自 2.6 起可用).

<预><代码>>>>从数字导入数字...从十进制导入十进制...从分数导入分数... 对于 [2, 2.0, Decimal('2.0'), complex(2, 0), Fraction(2, 1), '2'] 中的 n:...打印(f'{n!r:>14} {isinstance(n, Number)}')2 真2.0 真十进制('2.0')真(2+0j) 真分数(2, 1) 真'2' 错误

这当然与鸭子打字相反.如果您更关心一个对象如何作用而不是它是什么,请像您有一个数字一样执行您的操作,并使用异常来告诉您其他情况.

Given an arbitrary python object, what's the best way to determine whether it is a number? Here is is defined as acts like a number in certain circumstances.

For example, say you are writing a vector class. If given another vector, you want to find the dot product. If given a scalar, you want to scale the whole vector.

Checking if something is int, float, long, bool is annoying and doesn't cover user-defined objects that might act like numbers. But, checking for __mul__, for example, isn't good enough because the vector class I just described would define __mul__, but it wouldn't be the kind of number I want.

解决方案

Use Number from the numbers module to test isinstance(n, Number) (available since 2.6).

>>> from numbers import Number
... from decimal import Decimal
... from fractions import Fraction
... for n in [2, 2.0, Decimal('2.0'), complex(2, 0), Fraction(2, 1), '2']:
...     print(f'{n!r:>14} {isinstance(n, Number)}')
              2 True
            2.0 True
 Decimal('2.0') True
         (2+0j) True
 Fraction(2, 1) True
            '2' False

This is, of course, contrary to duck typing. If you are more concerned about how an object acts rather than what it is, perform your operations as if you have a number and use exceptions to tell you otherwise.

这篇关于检查对象是否为数字的最pythonic方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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