X9BlackHead9X X9BlackHead9X - 1 year ago 71
Python Question

Python : How to know is there is a instantiation of a class in a container?

I am quite new to python, and I haven't figured out yet how to solve my quit simple problem. I did some research, but either I did not found or I didn't understand what to do with it... My question is :
How to know if there is an instanciation of a class in a container such as a list ;
I want to do something like

if class in list :

I know this is a really simple question but to be honest I can't find the proper syntax to make it work :/

Answer Source

You can use the isinstance built in function to test if an object is an instantiation of a certain class, and the any built in function to test if any of the members of an iterable match your condition:

>>> class A:

>>> stuff = [1,2,A()]
>>> any(isinstance(a, A) for a in stuff)

FYI: all objects in Python are instantiations of some kind of class (even classes themselves!), so there's no point to seeing if an object in a list is an instantiation of any class, since everything in the list will be.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download