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


当前回答

如何确定Python中的变量类型?

因此,如果您有一个变量,例如:

one = 1

你想知道它的类型吗?

在Python中,有正确的方法和错误的方法可以做任何事情。这是正确的方法:

使用类型

>>> type(one)
<type 'int'>

您可以使用__name__属性获取对象的名称。(这是少数需要使用__dunder__名称才能访问的特殊属性之一——inspect模块中甚至没有一个方法。)

>>> type(one).__name__
'int'

不要使用__class__

在Python中,以下划线开头的名称在语义上不是公共API的一部分,用户最好避免使用它们。(除非绝对必要。)

由于类型为我们提供了对象的类,因此我们应该避免直接获取该类

>>> one.__class__

这通常是人们在访问方法中对象类型时的第一个想法——他们已经在寻找属性,所以类型看起来很奇怪。例如:

class Foo(object):
    def foo(self):
        self.__class__

不要。而是键入(self):

class Foo(object):
    def foo(self):
        type(self)

int和float的实现细节

如何查看变量的类型,无论它是无符号32位、有符号16位等。?

在Python中,这些细节是实现细节。所以,一般来说,我们在Python中通常不会担心这一点。然而,为了满足你的好奇心。。。

在Python 2中,int通常是一个有符号整数,等于实现的字宽(受系统限制)。它通常在C中实现为long。当整数大于此值时,我们通常将它们转换为Python long(精度无限,不要与C long混淆)。

例如,在32位Python 2中,我们可以推断int是一个有符号的32位整数:

>>> import sys

>>> format(sys.maxint, '032b')
'01111111111111111111111111111111'
>>> format(-sys.maxint - 1, '032b') # minimum value, see docs.
'-10000000000000000000000000000000'

在Python3中,旧的int已经消失,我们只使用(Python的)long作为int,它具有无限的精度。

我们还可以获得一些关于Python的浮点数的信息,这些浮点数通常在C中实现为double:

>>> 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__(一个语义上非公共的API)来获取变量的类型。请改用类型。

不要太担心Python的实现细节。我不必亲自处理这方面的问题。你可能也不会,如果你真的这样做了,你应该知道,不要去寻找这个答案。

其他回答

还有一种使用__class__的方法:

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

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

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

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.

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

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