Python check instances of classes
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 want to check that an object of user defined class and not instance of concrete built-in types you can check if it has __dict__
attribute.
>>> class A:... pass... >>> obj = A()>>> hasattr(obj, '__dict__')True>>> hasattr((1,2), '__dict__')False>>> hasattr(['a', 'b', 1], '__dict__')False>>> hasattr({'a':1, 'b':2}, '__dict__')False>>> hasattr({'a', 'b'}, '__dict__')False>>> hasattr(2, '__dict__')False>>> hasattr('hello', '__dict__')False>>> hasattr(2.5, '__dict__')False>>>
If you are interested in checking if an instance is an object of any class whether user defined or concrete you can simply check if it is an instance of object
which is ultimate base class in python.
class A: passa = A()isinstance(a, object)Trueisinstance(4, object)Trueisinstance("hello", object)Trueisinstance((1,), object)True