有没有一种简单的方法来确定变量是列表、字典还是其他什么?
当前回答
尝试一下可能会更像蟒蛇。。。除了块。这样,如果你有一个像列表一样嘎嘎作响的类,或者像格言一样嘎嘎作响,那么不管它的类型是什么,它都会表现得很好。
为了澄清,“区分”变量类型的首选方法是鸭子类型:只要变量响应的方法(和返回类型)是您的子例程所期望的,就要像您期望的那样对待它。例如,如果您有一个类用getattr和setattr重载括号运算符,但使用了一些有趣的内部方案,如果这正是它试图模仿的,那么它应该像一本字典一样。
类型(A)的另一个问题是类型(B)检查,如果A是B的子类,那么当您希望它是真的时,它的计算结果为假。如果一个对象是一个列表的子类,那么它应该像列表一样工作:检查另一个答案中显示的类型将防止这种情况发生。(然而,这一点是可行的)。
其他回答
小心使用isinstance
isinstance(True, bool)
True
>>> isinstance(True, int)
True
但类型
type(True) == bool
True
>>> type(True) == int
False
在许多实际情况下,您也可以使用@functools.singledispatch来定义泛型函数(由多个函数组成的函数,对不同类型执行相同的操作),而不是使用类型或isinstance。
换句话说,当您有如下代码时,您可能希望使用它:
def do_something(arg):
if isinstance(arg, int):
... # some code specific to processing integers
if isinstance(arg, str):
... # some code specific to processing strings
if isinstance(arg, list):
... # some code specific to processing lists
... # etc
下面是一个工作原理的小示例:
from functools import singledispatch
@singledispatch
def say_type(arg):
raise NotImplementedError(f"I don't work with {type(arg)}")
@say_type.register
def _(arg: int):
print(f"{arg} is an integer")
@say_type.register
def _(arg: bool):
print(f"{arg} is a boolean")
>>> say_type(0)
0 is an integer
>>> say_type(False)
False is a boolean
>>> say_type(dict())
# long error traceback ending with:
NotImplementedError: I don't work with <class 'dict'>
此外,我们可以使用抽象类同时覆盖几种类型:
from collections.abc import Sequence
@say_type.register
def _(arg: Sequence):
print(f"{arg} is a sequence!")
>>> say_type([0, 1, 2])
[0, 1, 2] is a sequence!
>>> say_type((1, 2, 3))
(1, 2, 3) is a sequence!
虽然这些问题很古老,但我在自己找到正确的方法时偶然发现了这一点,我认为它仍然需要澄清,至少对于Python2.x是如此(没有检查Python3,但由于这个问题出现在此类版本中的经典类中,这可能无关紧要)。
在这里,我试图回答标题的问题:如何确定任意对象的类型?其他关于使用或不使用isinstance的建议在许多评论和回答中都很好,但我并没有解决这些问题。
type()方法的主要问题是它不能在旧样式实例中正常工作:
class One:
pass
class Two:
pass
o = One()
t = Two()
o_type = type(o)
t_type = type(t)
print "Are o and t instances of the same class?", o_type is t_type
执行此代码段将产生:
Are o and t instances of the same class? True
我认为,这并不是大多数人所期望的。
__class__方法最接近正确性,但在一个关键的情况下,它不起作用:当传入的对象是旧式类(不是实例!)时,因为这些对象缺少这种属性。
这是我能想到的以一致方式满足此类合法问题的最小代码片段:
#!/usr/bin/env python
from types import ClassType
#we adopt the null object pattern in the (unlikely) case
#that __class__ is None for some strange reason
_NO_CLASS=object()
def get_object_type(obj):
obj_type = getattr(obj, "__class__", _NO_CLASS)
if obj_type is not _NO_CLASS:
return obj_type
# AFAIK the only situation where this happens is an old-style class
obj_type = type(obj)
if obj_type is not ClassType:
raise ValueError("Could not determine object '{}' type.".format(obj_type))
return obj_type
可以使用type()或isinstance()。
>>> type([]) is list
True
请注意,通过在当前作用域中分配同名变量,可以删除列表或任何其他类型。
>>> the_d = {}
>>> t = lambda x: "aight" if type(x) is dict else "NOPE"
>>> t(the_d) 'aight'
>>> dict = "dude."
>>> t(the_d) 'NOPE'
上面我们看到dict被重新分配给一个字符串,因此测试:
type({}) is dict
…失败。
要解决此问题并更谨慎地使用type():
>>> import __builtin__
>>> the_d = {}
>>> type({}) is dict
True
>>> dict =""
>>> type({}) is dict
False
>>> type({}) is __builtin__.dict
True
使用类型()
x='hello this is a string'
print(type(x))
输出
<class 'str'>
要仅提取str,请使用
x='this is a string'
print(type(x).__name__)#you can use__name__to find class
输出
str
如果使用类型(变量)__name__我们可以读
推荐文章
- Numpy Max vs amax vs maximum
- 我应该在.gitignore文件中添加Django迁移文件吗?
- 每n行有熊猫
- 实例属性attribute_name定义在__init__之外
- 如何获取在Python中捕获的异常的名称?
- 第一次出现的值大于现有值的Numpy
- 如何从Python函数中返回两个值?
- 前一个月的Python日期
- Python中方括号括起来的列表和圆括号括起来的列表有什么区别?
- Python日志记录不输出任何东西
- 每n秒运行特定代码
- SQLAlchemy是否有与Django的get_or_create等价的函数?
- 如何将python datetime转换为字符串,具有可读格式的日期?
- 美丽的汤和提取div及其内容的ID
- 在Python中重置生成器对象