Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python check instances of classes

Is there any way to check if object is an instance of a class? Not an instance of a concrete class, but an instance of any class.

I can check that an object is not a class, not a module, not a traceback etc., but I am interested in a simple solution.

like image 870
exbluesbreaker Avatar asked Jan 27 '13 16:01

exbluesbreaker


People also ask

How do I see all instances of class in Python?

To print all instances of a class with Python, we can use the gc module. We have the A class and we create 2 instances of it, which we assigned to a1 and a2 . Then we loop through the objects in memory with gc. get_objects with a for loop.

How do you find the number of instances of a class in Python?

You can use dir() function, which returns all properties and functions in the current script, to count the numbers of instances of a certain class.

How do I use Isinstance in Python?

Python isinstance() Function The isinstance() function returns True if the specified object is of the specified type, otherwise False . If the type parameter is a tuple, this function will return True if the object is one of the types in the tuple.


2 Answers

isinstance() is your friend here. It returns a boolean and can be used in the following ways to check types.

if isinstance(obj, (int, long, float, complex)):     print obj, "is a built-in number type"  if isinstance(obj, MyClass):     print obj, "is of type MyClass" 

Hope this helps.

like image 151
Matt Alcock Avatar answered Oct 19 '22 07:10

Matt Alcock


Have you tried isinstance() built in function?

You could also look at hasattr(obj, '__class__') to see if the object was instantiated from some class type.

like image 32
Ber Avatar answered Oct 19 '22 06:10

Ber