By tjvr

2010-10-25 14:15:26 8 Comments

Is there any reason for a class declaration to inherit from object?

I just found some code that does this and I can't find a good reason why.

class MyClass(object):
    # class code follows...


@Yarin 2012-02-25 21:15:32

Python 3

  • class MyClass(object): = New-style class
  • class MyClass: = New-style class (implicitly inherits from object)

Python 2

  • class MyClass(object): = New-style class
  • class MyClass: = OLD-STYLE CLASS


When defining base classes in Python 3.x, you’re allowed to drop the object from the definition. However, this can open the door for a seriously hard to track problem…

Python introduced new-style classes back in Python 2.2, and by now old-style classes are really quite old. Discussion of old-style classes is buried in the 2.x docs, and non-existent in the 3.x docs.

The problem is, the syntax for old-style classes in Python 2.x is the same as the alternative syntax for new-style classes in Python 3.x. Python 2.x is still very widely used (e.g. GAE, Web2Py), and any code (or coder) unwittingly bringing 3.x-style class definitions into 2.x code is going to end up with some seriously outdated base objects. And because old-style classes aren’t on anyone’s radar, they likely won’t know what hit them.

So just spell it out the long way and save some 2.x developer the tears.

@Aidis 2014-12-11 20:30:10

"When defining base classes in Python 3.x, you’re allowed to drop the object from the definition. However, this can open the door for a seriously hard to track problem…" What problems are you refering to?

@ShadowRanger 2016-12-09 02:07:26

@Aidis: I think they mean that code that runs on both Py2 and Py3 would be fine on Py3, but be broken on Py2 if it relies on new-style class features. Personally, if I'm writing code like that, I omit the explicit inheritance and just put __metaclass__ = type at the top of the module (after the from __future__ import absolute_import, division, print_function line :-) ); it's a compatibility hack in Py2 that makes all subsequently defined classes in the module new-style by default, and in Py3, it's completely ignored (just a random global variable sitting around), so it's harmless.

@Dimitris Fasarakis Hilliard 2017-07-12 15:34:59

Is there any reason for a class declaration to inherit from object?

In Python 3, apart from compatibility between Python 2 and 3, no reason. In Python 2, many reasons.

Python 2.x story:

In Python 2.x (from 2.2 onwards) there's two styles of classes depending on the presence or absence of object as a base-class:

  1. "classic" style classes: they don't have object as a base class:

    >>> class ClassicSpam:      # no base class
    ...     pass
    >>> ClassicSpam.__bases__
  2. "new" style classes: they have, directly or indirectly (e.g inherit from a built-in type), object as a base class:

    >>> class NewSpam(object):           # directly inherit from object
    ...    pass
    >>> NewSpam.__bases__
    (<type 'object'>,)
    >>> class IntSpam(int):              # indirectly inherit from object...
    ...    pass
    >>> IntSpam.__bases__
    (<type 'int'>,) 
    >>> IntSpam.__bases__[0].__bases__   # ... because int inherits from object  
    (<type 'object'>,)

Without a doubt, when writing a class you'll always want to go for new-style classes. The perks of doing so are numerous, to list some of them:

  • Support for descriptors. Specifically, the following constructs are made possible with descriptors:

    1. classmethod: A method that receives the class as an implicit argument instead of the instance.
    2. staticmethod: A method that does not receive the implicit argument self as a first argument.
    3. properties with property: Create functions for managing the getting, setting and deleting of an attribute.
    4. __slots__: Saves memory consumptions of a class and also results in faster attribute access. Of course, it does impose limitations.
  • The __new__ static method: lets you customize how new class instances are created.

  • Method resolution order (MRO): in what order the base classes of a class will be searched when trying to resolve which method to call.

  • Related to MRO, super calls. Also see, super() considered super.

If you don't inherit from object, forget these. A more exhaustive description of the previous bullet points along with other perks of "new" style classes can be found here.

One of the downsides of new-style classes is that the class itself is more memory demanding. Unless you're creating many class objects, though, I doubt this would be an issue and it's a negative sinking in a sea of positives.

Python 3.x story:

In Python 3, things are simplified. Only new-style classes exist (referred to plainly as classes) so, the only difference in adding object is requiring you to type in 8 more characters. This:

class ClassicSpam:

is completely equivalent (apart from their name :-) to this:

class NewSpam(object):

and to this:

class Spam():

All have object in their __bases__.

>>> [object in cls.__bases__ for cls in {Spam, NewSpam, ClassicSpam}]
[True, True, True]

So, what should you do?

In Python 2: always inherit from object explicitly. Get the perks.

In Python 3: inherit from object if you are writing code that tries to be Python agnostic, that is, it needs to work both in Python 2 and in Python 3. Otherwise don't, it really makes no difference since Python inserts it for you behind the scenes.

@bruno desthuilliers 2018-03-19 15:31:18

"depending on the presence or absence of a built-in type as a base-class" => actually it's not about "absence or presence of a builtin type as a base class" but wether the class inherits - directly or indirectly - from object. IIRC there was a point in time where not all builtin types where ported to new-style classes yet.

@Dimitris Fasarakis Hilliard 2018-03-20 09:50:14

@brunodesthuilliers My impression was that all built-in types did inherit from object. I do have a Python 2.2.3 around and after a quick check I couldn't find an offender but, I'll reword the answer later to make it more clear. Would be interested if you could find an example though, my curiosity is piqued.

@bruno desthuilliers 2018-03-20 11:18:02

In all honesty (cf the "IIRC" in my previous comment) I am not 101% sure about this point (wether all builtin types were already converted to new-style classes when new-style classes were introduced) - I might just be plain wrong, or this might only have concerned some of the standard lib's (but not builtin) types. But yet I think it should be better to clarify that what makes a new-style class is having object in it's bases.

@PirateApp 2018-07-16 04:35:50

too bad stackoverflow only does upvote = upvote + 1 for these kinda answers, wish I could do upvote += N

@ShadowRanger 2019-04-02 00:26:16

staticmethod and classmethod work just fine even on old-style classes. property sorta works for reading on old-style classes, it just fails to intercept writes (so if you assign to the name, the instance gains an attribute of the given name that shadows the property). Also note that __slots__'s improvement to attribute access speed is mostly about undoing the loss that new-style class attribute access incurs, so it's not really a selling point of new-style classes (the memory savings are a selling point though).

@knitti 2010-10-25 14:20:34

Yes, it's historical. Without it, it creates an old-style class.

If you use type() on an old-style object, you just get "instance". On a new-style object you get its class.

@Joel Sjögren 2014-02-15 15:31:24

Also, if you use type() on an old-style class, you get "classobj" instead of "type".

@disp_name 2014-11-04 10:54:50

History from Learn Python the Hard Way:

Python's original rendition of a class was broken in many serious ways. By the time this fault was recognized it was already too late, and they had to support it. In order to fix the problem, they needed some "new class" style so that the "old classes" would keep working but you can use the new more correct version.

They decided that they would use a word "object", lowercased, to be the "class" that you inherit from to make a class. It is confusing, but a class inherits from the class named "object" to make a class but it's not an object really its a class, but don't forget to inherit from object.

Also just to let you know what the difference between new-style classes and old-style classes is, it's that new-style classes always inherit from object class or from another class that inherited from object:

class NewStyle(object):

Another example is:

class AnotherExampleOfNewStyle(NewStyle):

While an old-style base class looks like this:

class OldStyle():

And an old-style child class looks like this:

class OldStyleSubclass(OldStyle):

You can see that an Old Style base class doesn't inherit from any other class, however, Old Style classes can, of course, inherit from one another. Inheriting from object guarantees that certain functionality is available in every Python class. New style classes were introduced in Python 2.2

@abarnert 2015-05-04 09:30:53

Calling the root class object isn't all that confusing, and in fact it's pretty standard. Smalltalk has a root class named Object, and a root metaclass named Class. Why? Because, just as Dog is a class for dogs, Object is a class for objects, and Class is a class for classes. Java, C#, ObjC, Ruby, and most other class-based OO languages that people use today that have a root class use some variation of Object as the name, not just Python.

@Jerub 2010-10-25 14:20:56

Yes, this is a 'new style' object. It was a feature introduced in python2.2.

New style objects have a different object model to classic objects, and some things won't work properly with old style objects, for instance, super(), @property and descriptors. See this article for a good description of what a new style class is.

SO link for a description of the differences: What is the difference between old style and new style classes in Python?

@user395760 2010-10-25 14:33:05

+1 This. Note that old-style classes are gone in Python 3, so you only need to inherit from object in Python 2.

@alwbtc 2016-01-01 12:41:58

This is not a real answer. ı just gives reference to other articles. I think Yarin's answer should be accepted as the answer to this question.

@ViFI 2016-06-28 21:59:07

@alwbtc : This answer has something new too. For example mention of "super()" led me to another important one [here](… ).

@kmario23 2016-10-20 05:37:38

The syntax of the class creation statement:

class <ClassName>(superclass):
    #code follows

In the absence of any other superclasses that you specifically want to inherit from, the superclass should always be object, which is the root of all classes in Python.

object is technically the root of "new-style" classes in Python. But the new-style classes today are as good as being the only style of classes.

But, if you don't explicitly use the word object when creating classes, then as others mentioned, Python 3.x implicitly inherits from the object superclass. But I guess explicit is always better than implicit (hell)


Related Questions

Sponsored Content

24 Answered Questions

[SOLVED] What is the purpose of the word 'self'?

  • 2010-04-25 20:22:28
  • richzilla
  • 866692 View
  • 1148 Score
  • 24 Answer
  • Tags:   python class oop self

26 Answered Questions

[SOLVED] Does Python have a ternary conditional operator?

21 Answered Questions

[SOLVED] Are static class variables possible in Python?

22 Answered Questions

[SOLVED] What are metaclasses in Python?

35 Answered Questions

[SOLVED] Interface vs Abstract Class (general OO)

27 Answered Questions

[SOLVED] Why not inherit from List&lt;T&gt;?

61 Answered Questions

[SOLVED] Calling an external command from Python

67 Answered Questions

[SOLVED] What is the most efficient way to deep clone an object in JavaScript?

Sponsored Content