如何检查一个变量是否是一个类? [英] How to check whether a variable is a class or not?

查看:61
本文介绍了如何检查一个变量是否是一个类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何检查变量是否是类(不是实例!).

我曾尝试使用函数 isinstance(object, class_or_type_or_tuple) 来执行此操作,但我不知道类将具有什么类型.

例如在下面的代码中

class Foo: passisinstance(Foo, **???**) # 我想让这个返回 True.

我尝试将class"替换为???,但我意识到class 是python 中的一个关键字.

解决方案

更好:使用 inspect.isclass 函数.

<预><代码>>>>进口检验>>>X 类(对象):... 经过...>>>检查.isclass(X)真的>>>x = X()>>>isinstance(x, X)真的>>>y = 25>>>isinstance(y, X)错误的

I was wondering how to check whether a variable is a class (not an instance!) or not.

I've tried to use the function isinstance(object, class_or_type_or_tuple) to do this, but I don't know what type would a class will have.

For example, in the following code

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

I tried to substitute "class" with ???, but I realized that class is a keyword in python.

解决方案

Even better: use the inspect.isclass function.

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

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

这篇关于如何检查一个变量是否是一个类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆