首页 文章

如何确定Python变量的类型?

提问于
浏览
1114

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

我该如何看待它?

14 回答

  • 327

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

    所以,如果你有一个变量,例如:

    one = 1
    

    你想知道它的类型吗?

    在Python中,有正确的方法和错误的方法来做所有事情 . 这是正确的方法:

    使用类型

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

    您可以使用 __name__ 属性获取对象的名称 . (这是使用 __dunder__ 名称所需的少数特殊属性之一 - 在 inspect 模块中甚至没有方法 . )

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

    不要使用__class__

    In Python, names that start with underscores are semantically not a part of the public API, and it's a best practice for users to avoid using them. (除非绝对必要 . )

    由于 type 给了我们对象的类,我们应该避免直接得到它 . :

    >>> one.__class__
    

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

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

    别 . 相反,请键入(self):

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

    整数和浮动的实现细节

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

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

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

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

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

    在Python 3中,旧的int消失了,我们只使用(Python的)long作为int,它有unlimited precision.

    我们还可以获得有关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)
    

    结论

    不要使用语义上非公共API的 __class__ 来获取变量的类型 . 请改用 type .

    并且不要过多担心Python的实现细节 . 我自己不必处理这个问题 . 你可能也不会,如果你真的这样做,你应该知道不要为这个答案寻找答案 .

  • 36

    你的意思是Python还是使用ctypes

    在第一种情况下,你根本不能 - 因为Python没有签名/无符号,16/32位整数 .

    在第二种情况下,您可以使用 type()

    >>> import ctypes
    >>> a = ctypes.c_uint() # unsigned int
    >>> type(a)
    <class 'ctypes.c_ulong'>
    

    有关ctypes及其类型的更多参考,请参阅the official documentation .

  • 24

    这个问题有点含糊不清 - 我不确定你的意思"view" . 如果您正在尝试查询本机Python对象的类型,_88432的答案将引导您朝着正确的方向前进 .

    但是,如果您尝试生成具有原始C类型语义的Python对象(例如 uint32_tint16_t ),请使用struct模块 . 您可以确定给定C类型原语中的位数:

    >>> struct.calcsize('c') # char
    1
    >>> struct.calcsize('h') # short
    2
    >>> struct.calcsize('i') # int
    4
    >>> struct.calcsize('l') # long
    4
    

    这也反映在 array 模块中,它可以生成这些较低级别类型的数组:

    >>> 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)
    
  • 19

    Python没有与C / C相同的类型,这似乎是您的问题 .

    试试这个:

    >>> i = 123
    >>> type(i)
    <type 'int'>
    >>> type(i) is int
    True
    >>> i = 123456789L
    >>> type(i)
    <type 'long'>
    >>> type(i) is long
    True
    >>> i = 123.456
    >>> type(i)
    <type 'float'>
    >>> type(i) is float
    True
    

    但是,在Python 3.0中,int和long之间的区别消失了 .

  • 146

    这取决于你的意思 . 在Python 2.x中,由于历史原因,有两种整数类型, int (约束为 sys.maxint )和 long (无限精度) . 在Python代码中,这不应该依赖于_88462的实现 . (CPython位于Objects / intobject.c和Objects / longobject.c中 . )要了解系统类型,请查看使用struct模块的cdleary答案 .

  • 15

    简单,对于python 3.4及以上版本

    print (type(variable_name))
    

    Python 2.7及以上版本

    print type(variable_name)
    
  • 36

    使用 __class__ 的另一种方法:

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

    在处理这样的问题时,我也强烈推荐使用IPython交互式解释器 . 它允许您键入 variable_name? 并返回有关该对象的完整信息列表,包括该类型的类型和文档字符串 .

    例如

    In [9]: var = 123
    
    In [10]: var?
    Type:       int
    Base Class: <type 'int'>
    String Form:    123
    Namespace:  Interactive
    Docstring:
        int(x[, base]) -> integer
    

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

  • 10

    Python没有您描述的类型 . 有两种类型用于表示整数值: int ,对应于C中平台的int类型,和 long ,这是一个任意精度整数(即它根据需要增长,没有上限) . 如果表达式产生的结果无法存储在 int 中,则 int 静默转换为 long .

  • 10

    您可能正在寻找 type() 功能 .

    请参阅下面的示例,但Python中没有像Java那样的“unsigned”类型 .

    正整数:

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

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

    assert type(variable_name) == int
    
    assert type(variable_name) == bool
    
    assert type(variable_name) == list
    
  • 86

    对于python2.x,请使用

    print type(variable_name)
    

    对于python3.x,请使用

    print(type(variable_name))
    
  • 18

    这可能有点无关紧要 . 但您可以使用 isinstance(object, type) 检查对象的类型,如here所述 .

  • 4

    这很简单 . 你这样做 .

    print(type(variable_name))
    

相关问题