How to check whether a variable is a class or not?

后端 未结 9 687
暖寄归人
暖寄归人 2020-11-28 19:14

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

9条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-28 19:21

    simplest way is to use inspect.isclass as posted in the most-voted answer.
    the implementation details could be found at python2 inspect and python3 inspect.
    for new-style class: isinstance(object, type)
    for old-style class: isinstance(object, types.ClassType)
    em, for old-style class, it is using types.ClassType, here is the code from types.py:

    class _C:
        def _m(self): pass
    ClassType = type(_C)
    

提交回复
热议问题