How to define what a class is ?

eryk sun eryksun at gmail.com
Thu Feb 25 06:21:43 EST 2016


On Thu, Feb 25, 2016 at 3:54 AM, ast <nomail at invalid.com> wrote:
> So we can conclude that inspect.isclass(x) is equivalent
> to isinstance(x, type)
>
> lets have a look at the source code of isclass:
>
> 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)

Except Python 2 old-style classes (i.e. 2.x classes that aren't a
subclass of `object`) are not instances of `type`. Prior to new-style
classes, only built-in types were instances of `type`. An old-style
class is an instance of "classobj", and its instances have the
"instance" type.

    >>> class A: pass
    ...
    >>> type(A)
    <type 'classobj'>
    >>> type(A())
    <type 'instance'>

Note that "classobj" and "instance" are instances of `type`.

The `isclass` check in Python 2 has to instead check
isinstance(object, (type, types.ClassType)).

    >>> types.ClassType
    <type 'classobj'>



More information about the Python-list mailing list