8

In one of my past questions, a answerer suggests me that it is better to inherit from object when the class you want to create is like from scratch, which is no need to inherit from other class.

For example, like what I always do:

class my_class:
     "a class inherits from nothing"
     def __init__(self):
         pass

For what he or she suggested:

class suggested_class(object):
     "a class inherits from object type"
     def __init__(self):
         pass

I am confused with the benefits or disadvantage from both approaches.

Question 1:

So what is your idea, inherit from object type or nothing?

3
  • 2
    see docs.python.org/release/2.2.3/whatsnew/… Commented Sep 5, 2011 at 5:15
  • As Marcello mentions, if you have two questions, please limit this post to a single question and post another question for the other. Commented Sep 5, 2011 at 5:35
  • You can have a look at dir(my_class) and dir(suggested_class). Furthermore, as mentioned below, both will be the same in Python3. Commented Sep 5, 2011 at 6:57

1 Answer 1

5

Inheriting from nothing creates an old-style class, which has different behaviour to new-style classes. I don't remember the specifics just now (see here for an explanation), but as a general rule, there's no reason to favour old-style classes, so you should always inherit from object (if nothing else).

Sign up to request clarification or add additional context in comments.

6 Comments

The reason for having new style classes is 1: the types of all instances of old style classes was classobj, which isn't very interesting, and 2: method resolution order on old style classes was broken for multiple inheritance. Fixing one or both of these issues would have made a lot of existing code stop working, so the simplest thing to do was make a different kind of class, thus object.
@Token Also, in Python 3, all classes are back to being new-style without specifically inheriting from object.
Well, old style classes were broken, and py3 intentionally breaks backward compatability, so that's a great time to make the jump.
@TokenMacGuy, Can you give more hint on why method resolution order on old style classes was broken for multiple inheritance? it seems unclear to me.
The short answer is that the old mro didn't preserve the order superclasses were listed in, So subclasses couldn't be sure what order the methods would be called in; for more details on the matter, read The Python 2.3 Method Resolution Order
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.