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


当前回答

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

其他回答

还有一种使用__class__的方法:

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

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

我在刚接触Python时(现在仍然如此)看到了这个:

x = …
print(type(x))```

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'>

对于python2.x,请使用

print type(variable_name)

对于python3.x,请使用

print(type(variable_name))