如何在 Python 中检查对象的类型?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35490420/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 16:30:19  来源:igfitidea点击:

How to check type of object in Python?

python

提问by Suzan Cioc

I have some value in variable v, how to check it's type?

我在变量中有一些值v,如何检查它的类型?

Hint: it is NOT v.dtype.

提示:它不是v.dtype

When I do type(v)in debugger, I get

当我type(v)在调试器中做时,我得到

type(v) = {type} <type 'h5py.h5r.Reference'>

or

或者

type(v) = {type} <class 'h5py._hl.dataset.Dataset'>

How to check these value at runtime?

如何在运行时检查这些值?

"Check" means calculate boolean result, saying if the type is given.

“检查”表示计算布尔结果,表示是否给出了类型。

UPDATE

更新

In so called "duplicate" question, it is said, that to compare type one should use

在所谓的“重复”问题中,据说,要比较类型一应该使用

type(v) is str

which implicitly assume that types are strings. Are they?

它隐含地假设类型是字符串。他们是吗?

回答by MSeifert

What type() means:

什么类型()意味着:

I think your question is a bit more general than I originally thought. type()with one argument returns the typeor classof the object. So if you have a = 'abc'and use type(a)this returns strbecause the variable ais a string. If b = 10, type(b)returns int.

我认为你的问题比我原先想象的更笼统。type()带一个参数返回对象的typeclass。所以如果你有a = 'abc'并使用type(a)它会返回,str因为变量a是一个字符串。如果b = 10,则type(b)返回int

See also python documentation on type().

另请参阅有关 type() 的 python 文档



For comparisons:

对于比较:

If you want a comparison you could use: if type(v) == h5py.h5r.Reference(to check if it is a h5py.h5r.Referenceinstance).

如果你想要一个比较,你可以使用:(if type(v) == h5py.h5r.Reference检查它是否是一个h5py.h5r.Reference实例)。

But it is recommended that one uses if isinstance(v, h5py.h5r.Reference)but then alsosubclasses will evaluate to True.

但建议一个使用if isinstance(v, h5py.h5r.Reference)但后来子类将评估到True

If you want to print the class use print v.__class__.__name__.

如果要打印类,请使用print v.__class__.__name__.

More generally: You can compare if two instances have the same class by using type(v) is type(other_v)or isinstance(v, other_v.__class__).

更一般地说:您可以使用type(v) is type(other_v)或比较两个实例是否具有相同的类isinstance(v, other_v.__class__)

回答by Henrikh Kantuni

use isinstance(v, type_name)or type(v) is type_nameor type(v) == type_name,

使用isinstance(v, type_name)type(v) is type_nametype(v) == type_name,

where type_namecan be one of the following:

其中type_name可以是以下之一:

  • None
  • bool
  • int
  • float
  • complex
  • str
  • list
  • tuple
  • set
  • dict
  • 没有任何
  • 布尔值
  • 整数
  • 漂浮
  • 复杂的
  • 字符串
  • 列表
  • 元组
  • 字典

and, of course,

而且当然,

  • custom types (classes)
  • 自定义类型(类)