检查python列表中是否有类的实例

时间:2019-04-02 12:39:49

标签: python

如果我有以下代码

class Person:
    pass
me = Person()

people = ['john','doe',me]

检查人员列表中是否存在Person实例的最佳方法是什么?

2 个答案:

答案 0 :(得分:3)

您可以使用isinstance来检查,

>>> class Person:
...   pass
...
>>> me = Person()
>>> people = ['john','doe',me]
>>> any(isinstance(x, Person) for x in people)
True

答案 1 :(得分:0)

您可以进行for循环

found=False
for element in people:
    if element == isinstance(element,Person):
        found = True
        break
print(found)