2

If I have an array of

g = ['hi']

Then

'hi' in g

returns True.

What if I put an instantiated class into an array.

g.append(MyClass())

How do I find if the array contains an object of this class.

MyClass in g

returns False

4

3 回答 3

3

使用isinstance()any()

In [95]: class A:pass

In [96]: lis=[A()]

In [97]: any(isinstance(x,A) for x in lis)
Out[97]: True

In [98]: lis=[1,2,3]

In [99]: any(isinstance(x,A) for x in lis)
Out[99]: False
于 2012-11-11T20:29:53.950 回答
1

Try this:

MyClass in [type(x) for x in g]

This will only find objects whose exact type is MyClass; it will not find objects of a class derived from MyClass. To do that, try one of the other answers that makes use of isinstance().

Example:

>>> class Foo(object): pass
...
>>> g = [1, 2, Foo(), 4]
>>> g
[1, 2, <__main__.Foo object at 0x7f59552ef750>, 4]
>>> Foo in [type(x) for x in g]
True
于 2012-11-11T20:29:14.730 回答
1
any(isinstance(x, MyClass) for x in g)
于 2012-11-11T20:29:28.977 回答