检查Python列表中是否有一个类的实例

2024-10-03 13:25:50 发布

您现在位置:Python中文网/ 问答频道 /正文

如果我有以下代码

class Person:
    pass
me = Person()

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

检查人员列表中是否有人员实例的最佳方法是什么?你知道吗


Tags: 实例方法代码列表人员passjohnpeople
2条回答

你可以用isinstance来检查

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

你可以做一个for循环

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

相关问题 更多 >