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

后端 未结 9 554
暖寄归人
暖寄归人 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:16

    There are some working solutions here already, but here's another one:

    >>> import types
    >>> class Dummy: pass
    >>> type(Dummy) is types.ClassType
    True
    
    0 讨论(0)
  • 2020-11-28 19:17

    This check is compatible with both Python 2.x and Python 3.x.

    import six
    isinstance(obj, six.class_types)
    

    This is basically a wrapper function that performs the same check as in andrea_crotti answer.

    Example:

    >>> import datetime
    >>> isinstance(datetime.date, six.class_types)
    >>> True
    >>> isinstance(datetime.date.min, six.class_types)
    >>> False
    
    0 讨论(0)
  • 2020-11-28 19:21

    The inspect.isclass is probably the best solution, and it's really easy to see how it's actually implemented

    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))
    
    0 讨论(0)
  • 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)
    
    0 讨论(0)
  • 2020-11-28 19:26

    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
    
    0 讨论(0)
  • 2020-11-28 19:28

    class Foo: is called old style class and class X(object): is called new style class.

    Check this What is the difference between old style and new style classes in Python? . New style is recommended. Read about "unifying types and classes"

    0 讨论(0)
提交回复
热议问题