1

What is the difference between these two methods of defining a class in python:

class TestClass(object):
    def __init__(self):
        pass

and

class TestClass:
    def __init__(self):
        pass

I don't understand the role of (object) in defining a class and I would appreciate your explanation of it. I did not find any answer to my question looking at the original documentation of python on classes here.

masoud
  • 11
  • 2
  • 1
    @IainShelvington. It's close, but not the same question. They go well together for sure. – Mad Physicist Aug 07 '21 at 02:53
  • In Python 3 there is no difference. It's done automatically. In Python 2, objects derived from `object` had a few additional capabilities. – Tim Roberts Aug 07 '21 at 02:54
  • If you are using a recent (still supported) Python version, there is none. If you are using Python 2, upgrade! – Klaus D. Aug 07 '21 at 02:57
  • Thanks for your answers, I now understand the reason and apparently it was a duplicate question. – masoud Aug 08 '21 at 05:04

2 Answers2

0

There's no difference. That syntax is used for defining inheritance, but all classes already inherit from object.

See section 9.5. Inheritance:

The syntax for a derived class definition looks like this:

class DerivedClassName(BaseClassName):

...

... all classes inherit from object ...


However, in Python 2, there was a difference. A class without (object) would be an old-style class, and one with (object) would be a new-style class, with more features.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
0

There is no difference starting with python 3. Any class that does not explicitly specify base classes inherits from object.

The notation class TestClass(object): is totally acceptable and unambiguous, but unnecessary and somewhat unconventional for modern code. It's a holdover from python 2.

When new-style classes were being introduced in python 2.2, users had to explicitly inherit from object to use the new functionality. Prior to python 3, class TestClass: would have created an old-style class, which would have indeed been different. Prior to python 2.2, object wasn't a thing.

You can read more about the history of the notation here: What is the difference between old style and new style classes in Python?

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264