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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With