Python check instances of classes

泄露秘密 提交于 2019-11-28 07:54:38

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
seaky

Yes. Accordingly, you can use hasattr(obj, '__dict__') or obj is not callable(obj).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!