如何查看变量的类型?(例如无符号32位)
当前回答
这很简单。你这样做。
print(type(variable_name))
其他回答
print type(variable_name)
在处理此类问题时,我也强烈建议使用IPython交互式解释器。它允许您键入variable_name?并将返回关于对象的完整信息列表,包括类型和类型的文档字符串。
e.g.
In [9]: var = 123
In [10]: var?
Type: int
Base Class: <type 'int'>
String Form: 123
Namespace: Interactive
Docstring:
int(x[, base]) -> integer
如果可能,将字符串或数字转换为整数。浮点参数将被截断为零(这不包括字符串浮点数的表示!)转换字符串时,请使用可选的基数。在转换非字符串。如果参数超出整数范围,则为长对象将返回。
使用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.
这取决于你的意思。在Python2.x中,由于历史原因,有两种整数类型,int(限制为sys.maxint)和long(无限精度)。在Python代码中,这不会有什么区别,因为当数字太大时,解释器会自动转换为long。如果您想了解底层解释器中使用的实际数据类型,这取决于实现。(CPython位于Objects/intobject.c和Objects/longobject.c中)要了解系统类型,请查看使用结构模块的cdleary答案。
没有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
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 使用try和。Python中的if
- 如何在Python中获得所有直接子目录