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


当前回答

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

您可能正在查找type()内置函数。

请参见下面的示例,但Python中没有像Java一样的“无符号”类型。

正整数:

>>> v = 10
>>> type(v)
<type 'int'>

大正整数:

>>> v = 100000000000000
>>> type(v)
<type 'long'>

负整数:

>>> v = -10
>>> type(v)
<type 'int'>

文字顺序:

>>> v = 'hi'
>>> type(v)
<type 'str'>

浮点整数:

>>> v = 3.14159
>>> type(v)
<type 'float'>

Python中的简单类型检查示例:

assert type(variable_name) == int

assert type(variable_name) == bool

assert type(variable_name) == list

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

my_variable = 5

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

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

这可能无关紧要。但您可以使用isinstance(object,type)检查对象的类型,如这里所述。