如何检查变量是否是python中的特定类?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18117729/
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 09:56:52  来源:igfitidea点击:

How to check if variable is a specific class in python?

python

提问by Rolando

I have a variable "myvar" that when I print out its type(myvar)

我有一个变量“myvar”,当我打印它时 type(myvar)

the output is:

输出是:

<class 'my.object.kind'>

If I have a list of 10 variables including strings and variables of that kind.. how can I construct an if statement to check whether an object in the list "mylist" is of <type 'my.object.kind'>?

如果我有一个包含 10 个变量的列表,包括字符串和那种类型的变量..如何构造一个 if 语句来检查列表“mylist”中的对象是否属于<type 'my.object.kind'>

采纳答案by zhangyangyu

Use isinstance, this will return true even if it is an instance of the subclass:

使用isinstance,即使它是子类的实例,这也会返回true:

if isinstance(x, my.object.kind)

Or:

或者:

type(x) == my.object.kind #3.x

If you want to test all in the list:

如果要测试列表中的所有内容:

if any(isinstance(x, my.object.kind) for x in alist)

回答by Owen

if any(map(lambda x: isinstance(x, my.object.kind), my_list_of_objects)):
    print "Found one!"

回答by lazy functor

Try

尝试

if any([isinstance(x, my.object.kind) for x in mylist]):
    print "found"