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.
Python 3
class MyClass(object):
= New-style classclass MyClass:
= New-style class (implicitly inherits from object
)Python 2
class MyClass(object):
= New-style classclass MyClass:
= OLD-STYLE CLASSExplanation:
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.