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


当前回答

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

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

还有一种使用__class__的方法:

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

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

assert type(variable_name) == int

assert type(variable_name) == bool

assert type(variable_name) == list

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