rmh
rmh

Reputation: 4907

Why would it be necessary to subclass from object in Python?

I've been using Python for quite a while now, and I'm still unsure as to why you would subclass from object. What is the difference between this:

class MyClass():
    pass

And this:

class MyClass(object):
    pass

As far as I understand, object is the base class for all classes and the subclassing is implied. Do you get anything from explicitly subclassing from it? What is the most "Pythonic" thing to do?

Upvotes: 15

Views: 3617

Answers (2)

wescpy
wescpy

Reputation: 11167

Agree with @kriss, @Noctis, and @Carson, plus more color from me:

class X: pass and class X(): pass are synonyms for classic classes while class X(object): pass is for new-style classes, as you can see here:

>>> class X:pass
... 
>>> class Y(): pass
... 
>>> class Z(object): pass
... 
>>> 
>>> type(X), type(Y), type(Z)
(<type 'classobj'>, <type 'classobj'>, <type 'type'>)

Look at the reference provided by @kriss for more details into the differences. What is invalid in Python 3 is the concept of the classic class... the reason is because classic classes have been deprecated. All three idioms create only new-style classes in any 3.x:

>>> class X:pass
... 
>>> class Y(): pass
... 
>>> class Z(object): pass
... 
>>> 
>>> type(X), type(Y), type(Z)
(<class 'type'>, <class 'type'>, <class 'type'>)

Bottom-line? If you're coding in Python 2, try to use new-style classes as much as possible. This way, you've built in your migration path already, plus new-style classes offer more features than classic classes do. (This is somewhat subjective, but if your [classic] classes are relatively simple, then it's possible you won't need to do anything to get them working in Python 3.)

Upvotes: 9

kriss
kriss

Reputation: 24177

This is oldstyle and new style classes in python 2.x. The second form is the up to date version and exist from python 2.2 and above. For new code you should only use new style classes.

In Python 3.x you can again use both form indifferently as the new style is the only one left and both form are truly equivalent. However I believe you should continue to use the MyClass(object) form even for 3.x code at least until python 3.x is widely adopted to avoid any misunderstanding with potential readers of your code used to 2.x.

Behavior between old style and new style classes is very different regarding to certain features like use of super().

See here : New Style classes

You can also see here on SO.

Upvotes: 12

Related Questions