如何检查变量是否为类?

2024-04-26 04:47:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道如何检查变量是否是类(而不是实例!)或者不。

我试过使用函数isinstance(object, class_or_type_or_tuple)来实现这一点,但我不知道类将具有什么类型。

例如,在下面的代码中

class Foo: pass  
isinstance(Foo, **???**) # i want to make this return True.

我试着用“class”代替“^{??”???,但我意识到class是python中的一个关键字。


Tags: orto实例函数代码类型makeobject
3条回答
>>> class X(object):
...     pass
... 
>>> type(X)
<type 'type'>
>>> isinstance(X,type)
True

更好的方法是:使用^{}函数。

>>> import inspect
>>> class X(object):
...     pass
... 
>>> inspect.isclass(X)
True

>>> x = X()
>>> isinstance(x, X)
True
>>> y = 25
>>> isinstance(y, X)
False

inspect.isclass可能是最好的解决方案,而且很容易看出它实际上是如何实现的

def isclass(object):
    """Return true if the object is a class.

    Class objects provide these attributes:
        __doc__         documentation string
        __module__      name of module in which this class was defined"""
    return isinstance(object, (type, types.ClassType))

相关问题 更多 >