如何确定 Python 变量的类型?
- 2024-12-25 08:51:00
- admin 原创
- 121
问题描述:
如何查看变量的类型?(例如无符号 32 位)
解决方案 1:
使用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++ 相同的类型,这似乎是您的问题。
解决方案 2:
您可能正在寻找内置函数。type()
请参见下面的示例,但与 Java 一样,Python 中没有“无符号”类型。
正整数:
>>> 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'>
解决方案 3:
非常简单。照着做就可以了。
print(type(variable_name))
解决方案 4:
Python中如何确定变量类型?
如果你有一个变量,例如:
one = 1
你想知道它的类型吗?
用 Python 做任何事情都有正确方法和错误方法。以下是正确的方法:
使用type
>>> 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 通常是一个有符号整数,等于实现的字宽(受系统限制)。在 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'
在 Python 3 中,旧的 int 消失了,我们只是使用(Python 的)long 作为 int,它具有无限的精度。
我们还可以获得一些有关 Python 浮点数的信息,它们在 C 中通常以双精度实现:
>>> 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 的实现细节。我自己还没有处理过这方面的问题。你可能也不会,如果你真的遇到了,你应该知道不要指望这个答案来决定怎么做。
解决方案 5:
print type(variable_name)
在处理此类问题时,我也强烈推荐IPythonvariable_name?
交互式解释器。它允许您键入并返回有关对象的完整信息列表,包括类型和类型的文档字符串。
例如
In [9]: var = 123
In [10]: var?
Type: int
Base Class: <type 'int'>
String Form: 123
Namespace: Interactive
Docstring:
int(x[, base]) -> integer
如果可能,将字符串或数字转换为整数。浮点参数将被截断为零(这不包括浮点数的字符串表示!)转换字符串时,使用可选的基数。转换非字符串时提供基数是错误的。如果参数超出整数范围,则将返回长对象。
解决方案 6:
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.
解决方案 7:
Python 中简单类型检查的示例:
assert type(variable_name) == int
assert type(variable_name) == bool
assert type(variable_name) == list
解决方案 8:
还有一个方法使用__class__
:
>>> a = [1, 2, 3, 4]
>>> a.__class__
<type 'list'>
>>> b = {'key1': 'val1'}
>>> b.__class__
<type 'dict'>
>>> c = 12
>>> c.__class__
<type 'int'>
解决方案 9:
这可能有点不相关。但您可以按照这里isinstance(object, type)
提到的方法检查对象的类型。
解决方案 10:
这个问题有点模棱两可——我不确定你所说的“视图”是什么意思。如果你试图查询本机 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 )由sys.maxintint
给出。
>>> 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)
解决方案 11:
你是指在Python中还是使用ctypes?
在第一种情况下,你根本不能——因为 Python 没有有符号/无符号、16/32 位整数。
在第二种情况下,您可以使用type()
:
>>> import ctypes
>>> a = ctypes.c_uint() # unsigned int
>>> type(a)
<class 'ctypes.c_ulong'>
有关 ctypes 及其类型的更多参考,请参阅官方文档。
解决方案 12:
Python 没有您描述的类型。有两种类型用于表示整数值:int
,对应于 C 中平台的 int 类型,以及long
,是任意精度的整数(即,它会根据需要增长并且没有上限)。如果表达式产生的结果无法存储在中,int
则 会被默默转换为。long
`int`
解决方案 13:
简单,适用于python 3.4及以上版本
print (type(variable_name))
Python 2.7 及更高版本
print type(variable_name)
解决方案 14:
我在刚接触 Python 的时候看到过这个(现在也是):
x = ...
print(type(x))
解决方案 15:
这实际上取决于你指的是哪个级别。在 Python 2.x 中,由于历史原因,有两种整数类型,int
(限制为sys.maxint
)和long
(无限精度)。在 Python 代码中,这应该不会有什么区别,因为当数字太大时,解释器会自动转换为 long。如果你想知道底层解释器中使用的实际数据类型,这取决于实现。(CPython 位于 Objects/intobject.c 和 Objects/longobject.c。)要了解系统类型,请查看使用 struct 模块的 cdleary 答案。
解决方案 16:
对于 python2.x,使用
print type(variable_name)
对于 python3.x,使用
print(type(variable_name))
解决方案 17:
你应该使用这个type()
函数。像这样:
my_variable = 5
print(type(my_variable)) # Would print out <class 'int'>
此函数将查看任何变量的类型,无论是列表还是类。查看此网站了解更多信息:https ://www.w3schools.com/python/ref_func_type.asp
解决方案 18:
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
让我们performances
在 python3 中比较一下这两种方法
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 loops, best of 5: 64.4 nsec per loop
isinstance 和 type 之间的区别
速度并不是这两个函数的唯一区别。它们的工作方式实际上有一个重要的区别:
type 仅返回对象的类型(它的类)。我们可以使用它来检查变量是否为 str 类型。
isinstance
检查给定对象(第一个参数)是否:作为第二个参数指定的类的实例。例如,变量是否是 str 类的实例?
或指定为第二个参数的类的子类的实例。换句话说 - 变量是 str 子类的实例吗?
这在实践中意味着什么?假设我们想要一个自定义类,它充当列表,但有一些额外的方法。因此,我们可以将列表类型子类化并在其中添加自定义函数:
class MyAwesomeList(list):
# Add additional functions here
pass
但是,如果我们将这个新类与列表进行比较,则类型和 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
。
解决方案 19:
没有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
解决方案 20:
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'>
解决方案 21:
Python 有一个 type() 函数用于此。你可以像这样简单地使用它:
variable = "I love apples."
print(type(variable)) # Output will be <class 'str'>
这意味着你的变量是一个字符串。
您可以用整数、浮点数、列表等自己尝试。
此外,通过使用 numpy 等库,你可以看到其他数据类型,例如:
import numpy as np
matrix = np.ones(shape=(3,3), dtype="uint8")
print(type(matrix)) # Output will be <class 'numpy.ndarray'>
print(type(matrix[0][0])) # Outpu will be <class 'numpy.uint8'>
您可以从这里了解有关 Python 中的数据类型的更多信息。
解决方案 22:
不要这么做。询问某种类型本身就是错误的。相反,使用多态性。找到或在必要时自己定义一个方法,该方法可以针对任何可能的输入类型执行您想要的操作,然后直接调用它而不询问任何事情。如果您需要使用内置类型或第三方库定义的类型,您可以随时从它们继承并使用您自己的派生类型。或者您可以将它们包装在您自己的类中。这是解决此类问题的面向对象方法。
如果您坚持检查确切类型并if
在这里或那里放置一些脏东西,您可以使用__class__
属性或type
函数来执行此操作,但很快您就会发现自己if
每两三次提交就会用附加案例更新所有这些 s。以 OO 方式执行此操作可以避免这种情况,并且您只需为新类型的输入定义一个新类即可。