本文介绍了Python检查isinstance列表中是否有任何类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我该怎么做:

var = 7.0
var_is_good = isinstance(var, classinfo1) or isinstance(var, classinfo2) or isinstance(var, classinfo3) or ... or  isinstance(var, classinfoN)

愚蠢的我不能只传递classinfo的列表:

It seems silly I can't just pass in a list of classinfo's:

var_is_good = isinstanceofany( var, [classinfo1, classinfo2, ... , classinfoN] )

那么isinstanceofany函数是什么?

推荐答案

isinstance()将类的 tuple 用作第二个参数.如果第一个参数是该序列中 any 类型的一个实例,则它将返回true:

isinstance() takes a tuple of classes for the second argument. It'll return true if the first argument is an instance of any of the types in that sequence:

isinstance(var, (classinfo1, classinfo2, classinfo3))

换句话说,isinstance() 已经已提供了现成的功能.

In other words, isinstance() already offers this functionality, out of the box.

> isinstance()文档:

强调地雷;注意递归性质; (classinfo1, (classinfo2, classinfo3))也是有效的选项.

Emphasis mine; note the recursive nature; (classinfo1, (classinfo2, classinfo3)) is also a valid option.

这篇关于Python检查isinstance列表中是否有任何类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-17 18:29