我想知道如何检查一个变量是否是一个类(不是一个实例!)
我尝试使用函数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中的关键字。
当前回答
检查。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))
其他回答
嗯,检查。Isclass不适合我,试试这个
class foo:
pass
var = foo()
if str(type(var)).split(".")[0] == "<class '__main__":
print("this is a class")
else:
print(str(type(var)).split(".")[0])
基本上,type(var)是<class 'a type'>
示例:<类'int' 但是,当var是一个类时,它将显示类似于<class '__main__.classname'>
因此,我们将字符串拆分为<class '__main__,并使用if进行比较,如果字符串完全匹配,则它是一个类
类Foo:称为旧样式类,类X(对象):称为新样式类。
Python中新旧风格类的区别是什么?. 推荐新款式。请阅读“统一类型和类”
在某些情况下(取决于你的系统),一个简单的测试是看看你的变量是否有__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__
最简单的方法是使用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)
这里已经有了一些可行的解决方案,但这里还有一个:
>>> import types
>>> class Dummy: pass
>>> type(Dummy) is types.ClassType
True