Cómo comprobar si una variable es una clase o no?


Me preguntaba cómo comprobar si una variable es una clase (no de una instancia!) o no.

He intentado usar la función isinstance(object, class_or_type_or_tuple) para hacer esto, pero no se qué tipo tendría una clase.

Por ejemplo, en el siguiente código

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

Traté de sustituir "class" con ???, pero me di cuenta de que class es una palabra clave en python.

Author: Martin Thoma, 2008-12-28

7 answers

Aún mejor: utilice el inspect.isclass función.

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

>>> x = X()
>>> isinstance(x, X)
True
>>> y = 25
>>> isinstance(y, X)
False
 247
Author: Benjamin Peterson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-16 23:23:47

La inspección.isclass es probablemente la mejor solución, y es muy fácil ver cómo se implementa en realidad

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))
 35
Author: andrea_crotti,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-04-12 12:24:08
>>> class X(object):
...     pass
... 
>>> type(X)
<type 'type'>
>>> isinstance(X,type)
True
 26
Author: S.Lott,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-12-28 03:11:54
isinstance(X, type)

Devuelve True si X es clase y False si no.

 14
Author: qnub,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-04-06 15:34:35

Clase Foo: se llama clase de estilo antiguo y clase X(objeto): se llama clase de estilo nuevo.

Compruebe esto ¿Cuál es la diferencia entre las clases de estilo antiguo y nuevo en Python? . Se recomienda un nuevo estilo. Leer sobre " unificar tipos y clases "

 1
Author: JV.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:34:44

La forma más sencilla es usar inspect.isclass como se publica en la respuesta más votada.
los detalles de la implementación se pueden encontrar en python2 inspect y python3 inspect .
para la clase de nuevo estilo: isinstance(object, type)
para la clase de estilo antiguo: isinstance(object, types.ClassType)
em, para la clase de estilo antiguo, está usando types.ClassType, aquí está el código de types.py :

class _C:
    def _m(self): pass
ClassType = type(_C)
 0
Author: lyu.l,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-30 07:56:26

Ya hay algunas soluciones que funcionan aquí, pero aquí hay otra:

>>> import types
>>> class Dummy: pass
>>> type(Dummy) is types.ClassType
True
 -2
Author: Ztyx,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-06-24 17:00:17