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.
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.
I'm late. anyway think this should work.
is_class = hasattr(obj, '__name__')
class test(object): pass
type(test)
returns
<type 'type'>
instance = test()
type(instance)
returns
<class '__main__.test'>
So that's one way to tell them apart.
def is_instance(obj):
import inspect, types
if not hasattr(obj, '__dict__'):
return False
if inspect.isroutine(obj):
return False
if type(obj) == types.TypeType: # alternatively inspect.isclass(obj)
# class type
return False
else:
return True
I think i am pretty late on this one, and infact was struggling with same issue. So here is what worked for me.
>>> 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
>>>
I tested this on both python 3 and 2.7.
I had a similar problem at this turned out to work for me:
def isclass(obj):
return isinstance(obj, type)
It's a bit hard to tell what you want, but perhaps inspect.isclass(val)
is what you are looking for?
or
import inspect
inspect.isclass(myclass)
Here's a dirt trick.
if str(type(this_object)) == "<type 'instance'>":
print "yes it is"
else:
print "no it isn't"
Had to deal with something similar recently.
import inspect
class A:
pass
def func():
pass
instance_a = A()
def is_object(obj):
return inspect.isclass(type(obj)) and not type(obj) == type
is_object(A) # False
is_object(func) # False
is_object(instance_a) # True
Yes. Accordingly, you can use hasattr(obj, '__dict__')
or obj is not callable(obj)
.
来源:https://stackoverflow.com/questions/14549405/python-check-instances-of-classes