我想知道如何检查一个变量是否是一个类(不是一个实例!)
我尝试使用函数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中的关键字。
当前回答
>>> class X(object):
... pass
...
>>> type(X)
<type 'type'>
>>> isinstance(X,type)
True
其他回答
在某些情况下(取决于你的系统),一个简单的测试是看看你的变量是否有__module__属性。
if getattr(my_variable,'__module__', None):
print(my_variable, ".__module__ is ",my_variable.__module__)
else:
print(my_variable,' has no __module__.')
Int, float, dict, list, STR等没有__module__
>>> class X(object):
... pass
...
>>> type(X)
<type 'type'>
>>> isinstance(X,type)
True
这里已经有了一些可行的解决方案,但这里还有一个:
>>> import types
>>> class Dummy: pass
>>> type(Dummy) is types.ClassType
True
最简单的方法是使用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)
类Foo:称为旧样式类,类X(对象):称为新样式类。
Python中新旧风格类的区别是什么?. 推荐新款式。请阅读“统一类型和类”