如何查看变量的类型?(例如无符号32位)
当前回答
使用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还是用ctypes?
在第一种情况下,您根本不可能——因为Python没有带符号/无符号的16/32位整数。
在第二种情况下,可以使用type():
>>> import ctypes
>>> a = ctypes.c_uint() # unsigned int
>>> type(a)
<class 'ctypes.c_ulong'>
有关ctypes及其类型的更多参考信息,请参阅官方文档。
这个问题有些模棱两可——我不确定你所说的“观点”是什么意思。如果您试图查询本地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)
这很简单。你这样做。
print(type(variable_name))
python中有许多数据类型,如:
Text Type: str
Numeric Types: int, float, complex
Sequence Types: list, tuple, range
Mapping Type: dict
Set Types: set, frozenset
Boolean Type: bool
Binary Types: bytes, bytearray, memoryview
None Type: NoneType
在这里,我写了一个代码,其中有一个包含所有类型数据类型的列表示例,并打印它们的类型
L = [
"Hello World",
20,
20.5,
1j,
["apple", "banana", "cherry"],
("apple", "banana", "cherry"),
range(6),
{"name" : "John", "age" : 36},
{"apple", "banana", "cherry"},
frozenset({"apple", "banana", "cherry"}),
True,
b"Hello",
bytearray(5),
memoryview(bytes(5)),
None
]
for _ in range(len(L)):
print(type(L[_]))
输出:
<class 'str'>
<class 'int'>
<class 'float'>
<class 'complex'>
<class 'list'>
<class 'tuple'>
<class 'range'>
<class 'dict'>
<class 'set'>
<class 'frozenset'>
<class 'bool'>
<class 'bytes'>
<class 'bytearray'>
<class 'memoryview'>
<class 'NoneType'>
使用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++相同的类型,这似乎是您的问题。
推荐文章
- 数据类vs类型。NamedTuple主要用例
- 如何从macOS完全卸载蟒蛇
- 是否有可能键入提示一个lambda函数?
- 'dict'对象没有has_key属性
- 使用Pandas groupby连接来自几行的字符串
- Pandas:给定列的数据帧行之和
- 如何避免在为Python项目构建Docker映像时重新安装包?
- 如何激活蟒蛇环境
- 省略[…]意思是在一个列表里?
- 为什么我得到“'str'对象没有属性'读取'”当尝试使用' json。载入字符串?
- 不区分大小写的列表排序,没有降低结果?
- 排序后的语法(key=lambda:…)
- 在烧瓶中返回HTTP状态代码201
- c++ auto关键字。为什么它是魔法?
- 使用python创建一个简单的XML文件