type, object hierarchy?

Jason tenax.raccoon at gmail.com
Sun Feb 3 23:06:18 EST 2008


On Feb 3, 8:36 pm, 7stud <bbxx789_0... at yahoo.com> wrote:
> print dir(type)      #__mro__ attribute is in here
> print dir(object)   #no __mro__ attribute
>
> class Mammals(object):
>     pass
> class Dog(Mammals):
>     pass
>
> print issubclass(Dog, type)   #False
> print Dog.__mro__
>
> --output:--
> (<class '__main__.Dog'>, <class '__main__.Mammals'>, <type 'object'>)
>
> The output suggests that Dog actually is a subclass of type--despite
> the fact that issubclass(Dog, type) returns False.  In addition, the
> output of dir(type) and dir(object):
>
> ['__base__', '__bases__', '__basicsize__', '__call__', '__class__',
> '__cmp__', '__delattr__', '__dict__', '__dictoffset__', '__doc__',
> '__flags__', '__getattribute__', '__hash__', '__init__',
> '__itemsize__', '__module__', '__mro__', '__name__', '__new__',
> '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__',
> '__subclasses__', '__weakrefoffset__', 'mro']
>
> ['__class__', '__delattr__', '__doc__', '__getattribute__',
> '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__',
> '__repr__', '__setattr__', '__str__']
>
> suggests that type inherits from object since type has all the same
> attributes as object plus some additional ones.  That seems to
> indicate a hierarchy like this:
>
> object
>  |
>  V
> type
>  |
>  V
> Mammals
>  |
>  V
> Dog
>
> But then why does issubclass(Dog, type) return False?

In your example, Mammal is directly derived from object, and Dog is
directly derived from Mammal.  Dog isn't derived from type, so it
isn't considered a subclass.  However, Python does create an instance
of class 'type' for each class you define.  That doesn't mean that
'type' is a superclass.  Try "isinstance(Dog, type)": it will return
True.

Type does inherit from object, but that's not what you're deriving
from.  The hierarchy that you're using is:

Dog
 ^
 |
Mammal
 ^
 |
object

As you notice, type isn't part of the object hierarchy for Dog.
That's why it doesn't show up in the MRO.  If you want to make Dog a
subclass of type, you'd need to do:

>>> class Dog(Mammal, type):
...     pass
...
>>> issubclass(Dog, type)
True

I don't know why'd you would want to do that, though.

  --Jason



More information about the Python-list mailing list