如何查看变量的类型?(例如无符号32位)


当前回答

对于python2.x,请使用

print type(variable_name)

对于python3.x,请使用

print(type(variable_name))

其他回答

Python没有您所描述的类型。有两种类型用于表示整数值:int,它对应于C中平台的int类型;long,它是一个任意精度的整数(即,它根据需要增长,没有上限)。如果表达式产生的结果无法存储在int中,则int将被无声地转换为long。

没有32位、64位和16位,python很简单,你不必担心。看看如何检查类型:

integer = 1
print(type(integer))  # Result: <class 'int'>, and if it's a string then class will be str and so on.

# Checking the type
float_class = 1.3
print(isinstance(float_class, float))  # True

但如果真的需要,可以使用Ctypes库,它具有无符号整数等类型。

Ctypes类型文档

您可以这样使用:

from ctypes import *
uint = c_uint(1)  # Unsigned integer
print(uint)  # Output: c_uint(1)

# To actually get the value, you have to call .value
print(uint.value)

# Change value
uint.value = 2
print(uint.value)  # 2

使用type()内置函数:

>>> i = 123
>>> type(i)
<type 'int'>
>>> type(i) is int
True
>>> i = 123.456
>>> type(i)
<type 'float'>
>>> type(i) is float
True

要检查变量是否为给定类型,请使用isinstance:

>>> i = 123
>>> isinstance(i, int)
True
>>> isinstance(i, (float, str, set, dict))
False

请注意,Python没有与C/C++相同的类型,这似乎是您的问题。

这个问题有些模棱两可——我不确定你所说的“观点”是什么意思。如果您试图查询本地Python对象的类型,@atzz的答案将引导您朝着正确的方向前进。

但是,如果您试图生成具有原始C类型语义的Python对象(例如uint32_t、int16_t),请使用结构模块。因此,您可以确定给定C型原语中的位数:

>>> struct.calcsize('c') # char
1
>>> struct.calcsize('h') # short
2
>>> struct.calcsize('i') # int
4
>>> struct.calcsize('l') # long
4

这也反映在数组模块中,它可以生成以下较低级别类型的数组:

>>> array.array('c').itemsize # char
1

支持的最大整数(Python 2的int)由sys.maxint给出。

>>> import sys, math
>>> math.ceil(math.log(sys.maxint, 2)) + 1 # Signedness
32.0

还有sys.getsizeof,它返回剩余内存中Python对象的实际大小:

>>> a = 5
>>> sys.getsizeof(a) # Residual memory.
12

对于浮点数据和精度数据,请使用sys.float_info:

>>> sys.float_info
sys.floatinfo(max=1.7976931348623157e+308, max_exp=1024, max_10_exp=308, min=2.2250738585072014e-308, min_exp=-1021, min_10_exp=-307, dig=15, mant_dig=53, epsilon=2.2204460492503131e-16, radix=2, rounds=1)

不要这样做。要求某种类型的东西本身就是错误的。而是使用多态性。查找或在必要时自行定义一个方法,该方法可以为任何可能类型的输入执行所需的操作,只需调用它,而无需询问任何问题。如果您需要使用内置类型或由第三方库定义的类型,您可以始终从它们继承并使用自己的派生类型。或者你可以把它们包装在自己的班级里。这是解决此类问题的面向对象方法。

如果你坚持要检查确切的类型,并在这里和那里放置一些肮脏的If,你可以使用__class__属性或类型函数来完成,但很快你就会发现自己每两次或三次提交就会更新所有这些If并添加额外的case。使用OO方法可以防止这种情况,并且只允许为新类型的输入定义一个新类。