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

后端 未结 9 555
暖寄归人
暖寄归人 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:32
    >>> class X(object):
    ...     pass
    ... 
    >>> type(X)
    <type 'type'>
    >>> isinstance(X,type)
    True
    
    0 讨论(0)
  • 2020-11-28 19:34

    Benjamin Peterson is correct about the use of inspect.isclass() for this job. But note that you can test if a Class object is a specific Class, and therefore implicitly a Class, using the built-in function issubclass. Depending on your use-case this can be more pythonic.

    from typing import Type, Any
    def isclass(cl: Type[Any]):
        try:
            return issubclass(cl, cl)
        except TypeError:
            return False
    

    Can then be used like this:

    >>> class X():
    ...     pass
    ... 
    >>> isclass(X)
    True
    >>> isclass(X())
    False
    
    0 讨论(0)
  • 2020-11-28 19:42
    isinstance(X, type)
    

    Return True if X is class and False if not.

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