sor*_*rin 44 python pep8 python-2.5
我发现了一些旧的Python代码,它们正在执行以下操作:
if type(var) is type(1):
...
Run Code Online (Sandbox Code Playgroud)
正如所料,pep8抱怨这个推荐用法isinstance().
现在,问题是该numbers模块是在Python 2.6中添加的,我需要编写适用于Python 2.5+的代码
所以if isinstance(var, Numbers.number)不是解决方案.
在这种情况下哪个是合适的解决方案?
Mar*_*ers 102
在Python 2中,您可以使用该types模块:
>>> import types
>>> var = 1
>>> NumberTypes = (types.IntType, types.LongType, types.FloatType, types.ComplexType)
>>> isinstance(var, NumberTypes)
True
Run Code Online (Sandbox Code Playgroud)
注意使用元组来测试多种类型.
引擎盖下,IntType只是别名int等:
>>> isinstance(var, (int, long, float, complex))
True
Run Code Online (Sandbox Code Playgroud)
该complex类型要求编译python时支持复数; 如果你想保护这个使用try/except块:
>>> try:
... NumberTypes = (types.IntType, types.LongType, types.FloatType, types.ComplexType)
... except AttributeError:
... # No support for complex numbers compiled
... NumberTypes = (types.IntType, types.LongType, types.FloatType)
...
Run Code Online (Sandbox Code Playgroud)
或者如果你直接使用这些类型:
>>> try:
... NumberTypes = (int, long, float, complex)
... except NameError:
... # No support for complex numbers compiled
... NumberTypes = (int, long, float)
...
Run Code Online (Sandbox Code Playgroud)
在Python 3中types不再具有任何标准类型别名,complex始终启用并且不再存在longvs int差异,因此在Python 3中始终使用:
NumberTypes = (int, float, complex)
Run Code Online (Sandbox Code Playgroud)
最后但并非最不重要的是,您可以使用numbers.Numbers抽象基类型(Python 2.6中的新增类)来支持不直接从上述类型派生的自定义数字类型:
>>> import numbers
>>> isinstance(var, numbers.Number)
True
Run Code Online (Sandbox Code Playgroud)
此检查也返回True了decimal.Decimal()和fractions.Fraction()对象.
该模块确实假设该complex类型已启用; 如果不是,你会得到一个导入错误.
Ash*_*ary 18
Python 2中支持四种类型为数字int,float,long和complex与python 3.x支持3: int,float和complex
>>> num = 10
>>> if isinstance(num, (int, float, long, complex)): #use tuple if checking against multiple types
print('yes it is a number')
yes it is a number
>>> isinstance(num, float)
False
>>> isinstance(num, int)
True
>>> a = complex(1, 2)
>>> isinstance(a, complex)
True
Run Code Online (Sandbox Code Playgroud)
# import numbers
isinstance(var, numbers.Number)
Run Code Online (Sandbox Code Playgroud)
告诉是否var是一个数字。例子:
import numbers
var = 5 ; print(isinstance(var, numbers.Number)) # True
var = 5.5; print(isinstance(var, numbers.Number)) # True
var = 'a'; print(isinstance(var, numbers.Number)) # False
import numpy as np
var = np.float128(888); print(isinstance(var, numbers.Number)) # True
class C: pass; var = C(); print(isinstance(var, numbers.Number)) # False
Run Code Online (Sandbox Code Playgroud)