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


当前回答

还有一种使用__class__的方法:

>>> a = [1, 2, 3, 4]
>>> a.__class__
<type 'list'>
>>> b = {'key1': 'val1'}
>>> b.__class__
<type 'dict'>
>>> c = 12
>>> c.__class__
<type 'int'>

其他回答

您可能正在查找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'>
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

如果可能,将字符串或数字转换为整数。浮点参数将被截断为零(这不包括字符串浮点数的表示!)转换字符串时,请使用可选的基数。在转换非字符串。如果参数超出整数范围,则为长对象将返回。

不要这样做。要求某种类型的东西本身就是错误的。而是使用多态性。查找或在必要时自行定义一个方法,该方法可以为任何可能类型的输入执行所需的操作,只需调用它,而无需询问任何问题。如果您需要使用内置类型或由第三方库定义的类型,您可以始终从它们继承并使用自己的派生类型。或者你可以把它们包装在自己的班级里。这是解决此类问题的面向对象方法。

如果你坚持要检查确切的类型,并在这里和那里放置一些肮脏的If,你可以使用__class__属性或类型函数来完成,但很快你就会发现自己每两次或三次提交就会更新所有这些If并添加额外的case。使用OO方法可以防止这种情况,并且只允许为新类型的输入定义一个新类。

还有一种使用__class__的方法:

>>> a = [1, 2, 3, 4]
>>> a.__class__
<type 'list'>
>>> b = {'key1': 'val1'}
>>> b.__class__
<type 'dict'>
>>> c = 12
>>> c.__class__
<type 'int'>

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