问题描述
给定一个任意的python对象,确定它是否是数字的最佳方法是什么?这里is
被定义为在某些情况下就像一个数字
.
例如,假设您正在编写一个向量类.如果给定另一个向量,您希望找到点积.如果给定一个标量,您希望缩放整个向量.
检查是否有 int
、float
、long
、bool
很烦人,并且不覆盖用户- 定义的对象可能像数字一样.但是,例如,检查 __mul__
还不够好,因为我刚刚描述的向量类将定义 __mul__
,但它不会是我所描述的那种数字想要.
使用 Number
来自 numbers
用于测试 isinstance(n, Number)
的模块(自 2.6 起可用).
这当然与鸭子打字相反.如果您更关心一个对象如何作用而不是它是什么,请像您有一个数字一样执行您的操作,并使用异常来告诉您其他情况.
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方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!