smwikipedia
smwikipedia

Reputation: 64175

Difference between <type 'classobj'>, <type 'object'>?

According to here:

The __mro__ attribute of the type lists the method resolution search order used by both getattr() and super(). The attribute is dynamic and can change whenever the inheritance hierarchy is updated.

I tried the __mro__ attribute with this:

class a:
    def __init__(self):
        self.testValue = 123

Then I typed:

type(a).__mro__
(<type 'classobj'>, <type 'object'>)

What's the classobj? And what's its difference with object?

ADD 1

Maybe I am a bit dizzy today... But I guess the classobj just means class a, right? So the above output just says the method resolution order is first class a then type object.

Upvotes: 4

Views: 3316

Answers (1)

bruno desthuilliers
bruno desthuilliers

Reputation: 77902

First note that in Python 2.x, the syntax:

class XXX:
    # whatever

will yield an "old style" class. You can read more about "old style" vs "new style" classes in the fine manual, on this doc page and in the Python wiki

Then, in your case, you're not asking for the mro of class a but for the mro of the type of class a (which is what type(a) returns), in this case the classobj type. But you shouldn't worry about old-style classes, classobj etc unless you have to maintain or deal with legacy code. For the record, most of Python's standard OO features (including super(), descriptors etc) won't work properly on old-style classes, so don't use them, and don't try to understand stuff pertaining to the "new" (well, about 10 years old by now ) object model using old-style classes...

TL;DR: you want:

class A(object):
    # this is a new-style class

Maybe I am a bit dizzy today... But I guess the classobj just means class a, right?

Wrong. classobj is a kind of a special type which serves as metaclass for old-style classes. The metaclass being the class of class (since classes are objects, they are instances of a class).

So the above output just says the method resolution order is first class a then type object.

No, it says that the mro for the classobj type is first classobj then object.

If you want the mro of class a then just ask for it - and then you'll find out why you shouldn't assess new-style features on old-style classes:

>>> class a: pass
... 
>>> a.__mro__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: class a has no attribute '__mro__'

Now compare with a new-style class:

>>> class Foo(object): pass
... 
>>> Foo.__mro__
(<class '__main__.Foo'>, <type 'object'>)
>>> 

Upvotes: 4

Related Questions