1

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?

Christopher Shroba
  • 7,006
  • 8
  • 40
  • 68
  • 2
    This is explained in the documentation per "old style vs new style" classes. Ultimately, in python 2, classes do not inherit from object. Python 3 addresses this. https://www.python.org/doc/newstyle/. The example you showed is using Python 3. – idjaw Dec 23 '16 at 15:11
  • 1
    I advise sticking with the `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)`. :) – PM 2Ring Dec 23 '16 at 15:24

1 Answers1

1

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.

DeepSpace
  • 78,697
  • 11
  • 109
  • 154
  • 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. – Christopher Shroba Dec 23 '16 at 16:17
  • @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. – DeepSpace Dec 23 '16 at 16:20
  • I see. Thanks for the comment! – Christopher Shroba Dec 23 '16 at 16:24