如何查看变量的类型? (例如无符号 32 位)
使用 type()
内置函数:
>>> i = 123
>>> type(i)
<type 'int'>
>>> type(i) is int
True
>>> i = 123.456
>>> type(i)
<type 'float'>
>>> type(i) is float
True
要检查变量是否属于给定类型,请使用 isinstance
:
>>> i = 123
>>> isinstance(i, int)
True
>>> isinstance(i, (float, str, set, dict))
False
请注意,Python 的类型与 C/C++ 不同,这似乎是您的问题。
您可能正在寻找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))
如何确定 Python 中的变量类型?
因此,如果您有一个变量,例如:
one = 1
你想知道它的类型吗?
在 Python 中做任何事情都有正确的方法和错误的方法。这是正确的方法:
使用类型
>>> type(one)
<type 'int'>
您可以使用 __name__
属性来获取对象的名称。 (这是您需要使用 __dunder__
名称来获得的少数特殊属性之一 - inspect
模块中甚至没有它的方法。)
>>> type(one).__name__
'int'
不要使用 __class__
在 Python 中,以下划线开头的名称在语义上不是公共 API 的一部分,用户最好避免使用它们。 (除非绝对必要。)
由于 type
为我们提供了对象的类,我们应该避免直接获取它。 :
>>> one.__class__
这通常是人们在方法中访问对象类型时的第一个想法——他们已经在寻找属性,所以类型看起来很奇怪。例如:
class Foo(object):
def foo(self):
self.__class__
不。相反,做类型(自我):
class Foo(object):
def foo(self):
type(self)
整数和浮点数的实现细节
如何查看变量的类型是无符号 32 位、有符号 16 位等?
在 Python 中,这些细节是实现细节。所以,一般来说,我们在 Python 中通常不会担心这个问题。不过,为了满足你的好奇心...
在 Python 2 中,int 通常是一个有符号整数,等于实现的 word 宽度(受系统限制)。它通常实现为 long in C。当整数变得比这更大时,我们通常将它们转换为 Python 长整数(精度不受限制,不要与 C 长整数混淆)。
例如,在 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's) long as 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)
结论
不要使用 __class__
(语义上非公共 API)来获取变量的类型。请改用 type
。
并且不用太担心 Python 的实现细节。我不必自己处理这方面的问题。你可能也不会,如果你真的这样做,你应该知道足够多,不要寻找这个答案来做什么。
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
如果可能,将字符串或数字转换为整数。浮点参数将被截断为零(这不包括浮点数的字符串表示形式!)转换字符串时,请使用可选的基数。转换非字符串时提供基数是错误的。如果参数超出整数范围,则会返回一个 long 对象。
print type(str)
在 Python 3.6 中返回错误。使用type(str)
print(type(str))
print type(var)
错误代码。
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.
使用 __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
type()
的结果,我们希望它进行类型检查,但具体方法并不明显(我假设您必须将类型作为字符串进行比较:if (type(var)=='str'):
)
这可能无关紧要。但您可以使用 isinstance(object, type)
检查对象的类型,如提到的 here。
这个问题有点模棱两可——我不确定你所说的“视图”是什么意思。如果您尝试查询原生 Python 对象的类型,@atzz 的回答将引导您朝着正确的方向前进。
但是,如果您尝试生成具有原始 C 类型语义的 Python 对象(例如 uint32_t
、int16_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)
在第一种情况下,您根本不能——因为 Python 没有带符号/无符号的 16/32 位整数。
在第二种情况下,您可以使用 type()
:
>>> import ctypes
>>> a = ctypes.c_uint() # unsigned int
>>> type(a)
<class 'ctypes.c_ulong'>
有关 ctypes 及其类型的更多参考,请参阅 the official documentation。
Python没有你描述的那种类型。有两种类型用于表示整数值:int
,对应于 C 中平台的 int 类型,以及 long
,它是任意精度整数(即它根据需要增长并且没有上限)。如果表达式产生的结果无法存储在 int
中,则 int
将被静默转换为 long
。
简单,适用于 python 3.4 及以上版本
print (type(variable_name))
Python 2.7 及以上
print type(variable_name)
这真的取决于你的意思是什么级别。在 Python 2.x 中,由于历史原因,有两种整数类型,int
(限制为 sys.maxint
)和 long
(无限精度)。在 Python 代码中,这应该没什么区别,因为当数字太大时,解释器会自动转换为 long。如果您想了解底层解释器中使用的实际数据类型,那取决于实现。 (CPython 位于 Objects/intobject.c 和 Objects/longobject.c。)要了解系统类型,请查看使用 struct 模块的 cdleary 答案。
对于 python2.x,使用
print type(variable_name)
对于 python3.x,使用
print(type(variable_name))
您应该使用 type()
函数。像这样:
my_variable = 5
print(type(my_variable)) # Would print out <class 'int'>
此函数将查看任何变量的类型,无论是列表还是类。查看此网站了解更多信息:https://www.w3schools.com/python/ref_func_type.asp
Python 是一种动态类型语言。最初创建为字符串的变量可以稍后重新分配给整数或浮点数。口译员不会抱怨:
name = "AnyValue"
# Dynamically typed language lets you do this:
name = 21
name = None
name = Exception()
要检查变量的类型,您可以使用 type() 或 isinstance() 内置函数。让我们看看他们的行动:
Python3 示例:
variable = "hello_world"
print(type(variable) is str) # True
print(isinstance(variable, str)) # True
让我们比较一下python3中的两种方法performances
python3 -m timeit -s "variable = 'hello_world'" "type(variable) is int"
5000000 loops, best of 5: 54.5 nsec per loop
python3 -m timeit -s "variable = 'hello_world'" "isinstance(variable, str)"
10000000 loops, best of 5: 39.2 nsec per loop
类型大约慢 40% (54.5/39.2 = 1.390)。
我们可以改用 type(variable) == str
。它会起作用,但这是一个坏主意:
当您要检查变量的值时,应使用 ==。我们将使用它来查看变量的值是否等于“hello_world”。但是当我们要检查变量是否为字符串时,is 运算符更为合适。有关何时使用其中一个或另一个的更详细说明,请查看本文。
== 较慢:python3 -m timeit -s "variable = 'hello_world'" "type(variable) == str" 5000000 个循环,最好的 5 个:每个循环 64.4 纳秒
isinstance 和 type 的区别
速度并不是这两个功能之间的唯一区别。它们的工作方式实际上有一个重要区别:
type 只返回对象的类型(它的类)。我们可以使用它来检查变量是否为 str 类型。
isinstance 检查给定对象(第一个参数)是否为:指定为第二个参数的类的实例。例如,变量是 str 类的实例吗?或指定为第二个参数的类的子类的实例。换句话说 - 变量是 str 的子类的实例吗?
指定为第二个参数的类的实例。例如,变量是 str 类的实例吗?
或指定为第二个参数的类的子类的实例。换句话说 - 变量是 str 的子类的实例吗?
在实践中意味着什么?假设我们想要一个自定义类,它充当一个列表,但有一些额外的方法。所以我们可以子类化列表类型并在里面添加自定义函数:
class MyAwesomeList(list):
# Add additional functions here
pass
但是现在如果我们将这个新类与列表进行比较,type 和 isinstance 返回不同的结果!
my_list = MyAwesomeList()
print(type(my_list) is list) # False
print(isinstance(my_list, list)) # True
我们得到不同的结果,因为 isinstance 检查 my_list
是列表的实例(不是)还是列表的子类(这是因为 MyAwesomeList
是列表的子类)。如果您忘记了这种差异,它可能会导致您的代码中出现一些细微的错误。
结论
isinstance
通常是比较类型的首选方式。它不仅更快,而且还考虑了继承,这通常是所需的行为。在 Python 中,您通常想要检查给定对象的行为是否像字符串或列表,不一定是字符串。因此,您可以使用 isinstance,而不是检查字符串及其所有自定义子类。
另一方面,当您想明确检查给定变量是否属于特定类型(而不是其子类)时,请使用 type
。并且当你使用它时,像这样使用它:type(var) is some_type
而不是这样:type(var) == some_type
。
"123"
,并且您事先不知道类型是什么,您会怎么做?
"123"
。可以在类型转换期间检查它,如 int(value)
。如果它不是整数值,它将抛出 ValueError: invalid literal for int() with base 10:
。也可以通过使用 try-except 块(如 try: value = int(value) except ValueError: print("Invalid integer value")
)优雅地捕获此异常
没有 32bit 和 64bit 和 16bit,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 库。
你可以像这样使用它:
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
只是不要这样做。询问某事的类型本身就是错误的。而是使用多态性。查找或在必要时自行定义对任何可能的输入类型执行所需操作的方法,然后直接调用它而不询问任何内容。如果您需要使用内置类型或第三方库定义的类型,您始终可以从它们继承并使用您自己的派生类。或者您可以将它们包装在您自己的类中。这是解决此类问题的面向对象的方法。
如果您坚持要检查确切的类型并在这里和那里放置一些脏 if
,您可以使用 __class__
属性或 type
函数来执行此操作,但很快您会发现自己更新了所有这些 if
每两个或三个提交的案例。以 OO 方式进行操作可以防止这种情况发生,并且只允许您为新类型的输入定义一个新类。
不定期副业成功案例分享