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


当前回答

对于python2.x,请使用

print type(variable_name)

对于python3.x,请使用

print(type(variable_name))

其他回答

这个问题有些模棱两可——我不确定你所说的“观点”是什么意思。如果您试图查询本地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)

没有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

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

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

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

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

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

使用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++相同的类型,这似乎是您的问题。

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.