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


当前回答

a = "cool"
type(a)

//result 'str'
<class 'str'>
or 
do 
`dir(a)` 
to see the list of inbuilt methods you can have on the variable.

其他回答

使用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)

你的意思是用Python还是用ctypes?

在第一种情况下,您根本不可能——因为Python没有带符号/无符号的16/32位整数。

在第二种情况下,可以使用type():

>>> import ctypes
>>> a = ctypes.c_uint() # unsigned int
>>> type(a)
<class 'ctypes.c_ulong'>

有关ctypes及其类型的更多参考信息,请参阅官方文档。

这取决于你的意思。在Python2.x中,由于历史原因,有两种整数类型,int(限制为sys.maxint)和long(无限精度)。在Python代码中,这不会有什么区别,因为当数字太大时,解释器会自动转换为long。如果您想了解底层解释器中使用的实际数据类型,这取决于实现。(CPython位于Objects/intobject.c和Objects/longobject.c中)要了解系统类型,请查看使用结构模块的cdleary答案。

您应该使用type()函数。像这样:

my_variable = 5

print(type(my_variable)) # Would print out <class 'int'>

此函数将查看任何变量的类型,无论是列表还是类。查看此网站了解更多信息:https://www.w3schools.com/python/ref_func_type.asp