I've always heard that it is best to inherit explicitly from object when creating classes in Python, but I noticed that in many examples on the Python website (For example,this, this convention is not used. Is there a reason for this?
1 Answer
These examples are using Python 3 (3.6 to be precised). "Old" vs "new" style classes was a thing in Python 2. In Python 3 all classes are "new style" classes.
3 Comments
Christopher Shroba
Sorry if I wasn't clear. I understand that there is no distinction in Python 3, but my question is regarding the choice to use
class Foo: vs class Foo(object): in Python3, knowing that both do the same thing.DeepSpace
@ChristopherShroba There is no reason to inherit from
object in Python 3 rather than keeping backward compatibility with Python 2 with the same code-base. If no such support is needed then it only clatters the code. You can also write if (x == 1): but you don't since it only adds visual clatter.Christopher Shroba
I see. Thanks for the comment!
class classname(object):convention at present, since it makes it easier to write code that will run correctly on both Python 3 & Python 2. OTOH, if you're writing code that is specifically for Python 3 that would be painful to make Python 2 compatible then feel free to drop the(object). :)