Python check instances of classes

﹥>﹥吖頭↗ 提交于 2019-11-27 21:10:39

问题


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.


回答1:


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.




回答2:


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.




回答3:


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



回答4:


I'm late. anyway think this should work.

is_class = hasattr(obj, '__name__')



回答5:


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.




回答6:


I had a similar problem at this turned out to work for me:

def isclass(obj):
    return isinstance(obj, type)



回答7:


It's a bit hard to tell what you want, but perhaps inspect.isclass(val) is what you are looking for?




回答8:


or

import inspect
inspect.isclass(myclass)



回答9:


Here's a dirt trick.

if str(type(this_object)) == "<type 'instance'>":
    print "yes it is"
else:
    print "no it isn't"



回答10:


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




回答11:


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


来源:https://stackoverflow.com/questions/14549405/python-check-instances-of-classes

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