简体   繁体   English

Python 检查类的实例

[英]Python check instances of classes

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. isinstance()是你的朋友。 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?您是否尝试过isinstance()内置函数?

You could also look at hasattr(obj, '__class__') to see if the object was instantiated from some class type.您还可以查看hasattr(obj, '__class__')以查看对象是否从某个类类型实例化。

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.如果您想检查用户定义类的对象而不是具体内置类型的实例,您可以检查它是否具有__dict__属性。

>>> 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.如果您有兴趣检查实例是否是任何类的对象,无论是用户定义的还是具体的,您可以简单地检查它是否是 Python 中最终基类的object的实例。

class A:
    pass
a = A()
isinstance(a, object)
True
isinstance(4, object)
True
isinstance("hello", object)
True
isinstance((1,), object)
True

I had a similar problem at this turned out to work for me:我有一个类似的问题,结果证明对我有用:

def isclass(obj):
    return isinstance(obj, 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

很难说出你想要什么,但也许inspect.isclass(val)是你正在寻找的?

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"

Yes.是的。 Accordingly, you can use hasattr(obj, '__dict__') or obj is not callable(obj) .因此,您可以使用hasattr(obj, '__dict__')obj is not callable(obj)

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.我可以检查一个对象不是一个类,不是一个模块,不是一个回溯等,但我对一个简单的解决方案感兴趣。

One approach, like you describe in your question, is a process of exclusion, check if it isn't what you want.一种方法,就像您在问题中描述的那样,是一个排除过程,检查它是否不是您想要的。 We check if it's a class, a module, a traceback, an exception, or a function.我们检查它是一个类、一个模块、一个回溯、一个异常还是一个函数。 If it is, then it's not a class instance.如果是,则它不是类实例。 Otherwise, we return True, and that's potentially useful in some cases, plus we build up a library of little helpers along the way.否则,我们返回 True,这在某些情况下可能很有用,而且我们在此过程中构建了一个小助手库。

Here is some code which defines a set of type checkers and then combines them all to exclude various things we don't care about for this problem.这里有一些代码定义了一组类型检查器,然后将它们全部组合起来以排除我们不关心这个问题的各种事情。

from types import (
    BuiltinFunctionType,
    BuiltinMethodType,
    FunctionType,
    MethodType,
    LambdaType,
    ModuleType,
    TracebackType,
)
from functools import partial
from toolz import curry
import inspect
    
def isfunction(variable: any) -> bool:
    return isinstance(
        variable,
        (
            BuiltinFunctionType,
            BuiltinMethodType,
            FunctionType,
            MethodType,
            LambdaType,
            partial,
            curry
        ),
    )
    
isclass = inspect.isclass
    
def ismodule(variable: any) -> bool:
   return isinstance(variable, ModuleType)
    
    
def isexception(variable: any) -> bool:
    return isinstance(variable, Exception)
    
    
def istraceback(variable: any) -> bool:
    return isinstance(variable, TracebackType)
    
    
def isclassinstance(x: any) -> bool:
    if isfunction(x) or isclass(x) or ismodule(x) or istraceback(x) or isexception(x):
        return False
    return True

keep in mind, from a hella abstract perspective, everything is a thing, even categories of things or functions ... but from a practical perspective, this could help avoid mistaking MyClass for my_class_instance (the python community also does this informally with PascalCase vs snake_case)请记住,从抽象的角度来看,一切都是事物,甚至事物的类别或功能......但从实际的角度来看,这有助于避免将 MyClass 误认为 my_class_instance(python 社区也使用 PascalCase 与 snake_case 非正式地做到这一点) )

we could improve this我们可以改进这一点

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM