我想知道如何检查一个变量是否是一个类(不是一个实例!)
我尝试使用函数isinstance(对象,class_or_type_or_tuple)来做到这一点,但我不知道一个类会有什么类型。
例如,在下面的代码中
class Foo: pass
isinstance(Foo, **???**) # i want to make this return True.
我试着用“阶级”来代替??,但我意识到class是python中的关键字。
我想知道如何检查一个变量是否是一个类(不是一个实例!)
我尝试使用函数isinstance(对象,class_or_type_or_tuple)来做到这一点,但我不知道一个类会有什么类型。
例如,在下面的代码中
class Foo: pass
isinstance(Foo, **???**) # i want to make this return True.
我试着用“阶级”来代替??,但我意识到class是python中的关键字。
当前回答
还有另一种检查方法:
import inspect
class cls():
print(None)
inspect.isclass(cls)
参考:https://www.kite.com/python/docs/inspect.isclass
其他回答
最简单的方法是使用inspect。是类张贴在投票最多的答案。 实现细节可以在python2 inspect和python3 inspect中找到。 对于new-style类:isinstance(object, type) 对于旧式类:isinstance(object, types.ClassType) 对于老式的类,它使用类型。下面是types.py的代码:
class _C:
def _m(self): pass
ClassType = type(_C)
>>> class X(object):
... pass
...
>>> type(X)
<type 'type'>
>>> isinstance(X,type)
True
isinstance(X, type)
如果X是类,则返回True,否则返回False。
类Foo:称为旧样式类,类X(对象):称为新样式类。
Python中新旧风格类的区别是什么?. 推荐新款式。请阅读“统一类型和类”
检查。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))