加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 如何识别变量是类还是对象

发布时间:2020-12-20 12:39:18 所属栏目:Python 来源:网络整理
导读:我正在更低层次上编写一个小框架,用于在 Python中为我的项目创建测试夹具.在这里我想知道一个特定的变量是某个类的实例还是一个类本身,如果它是一个类,我想知道它是否是我的框架定义的某个类的子类.我该怎么做? class MyBase(object): passclass A(MyBase):
我正在更低层次上编写一个小框架,用于在 Python中为我的项目创建测试夹具.在这里我想知道一个特定的变量是某个类的实例还是一个类本身,如果它是一个类,我想知道它是否是我的框架定义的某个类的子类.我该怎么做?

class MyBase(object):
    pass

class A(MyBase):
    a1 = 'Val1'
    a2 = 'Val2'

class B(MyBase):
    a1 = 'Val3'
    a2 = A

我想知道属性a1和a2是类/类型的实例(a1是B中的字符串类型)还是类对象本身(即a2是B中的A).你能帮我解决一下这个问题吗?

解决方法

使用 inspect module.

The inspect module provides several useful functions to help get information about live objects such as modules,classes,methods,functions,tracebacks,frame objects,and code objects. For example,it can help you examine the contents of a class,retrieve the source code of a method,extract and format the argument list for a function,or get all the information you need to display a detailed traceback.

例如,如果对象是类,则inspect.isclass()函数返回true:

>>> import inspect
>>> inspect.isclass(inspect)
False
>>> inspect.isclass(inspect.ArgInfo)
True
>>>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读