Python

Why should we use object in Python classes?

March 15, 2022

Why should we use object in Python classes?

In this article we will learn why in Python classes we should use the object and also what is the importance of this action for our software.

object in Python classes thumb

What’s up programmer, how are you? Let’s learn more about Python!

This issue of defining the object as an argument was defined in Python version number 3

These classes are called new-style, declaring the object argument, and those in version 2 are called old-style, with no argument.

In practice it is not mandatory to define the argument, the class works both ways (new and old)

The issue is that the code becomes more explicit, which is nailed in the Python documentation as Pythonic code

Noting that the class inherits the methods and properties of object, in a way that even those who are new to the language understand this set of characteristics and it doesn’t seem like it ‘came out of nowhere’

Check out the comparison:

class Test:
 pass

class Test(object):
 pass

The first example is a class created in the old-style and the second a class with the new-style

In addition, the new version of classes in Python 3 does not only bring these changes

Other positives aspects are:

  • The ability to use super, thus accessing superclass members directly;
  • The use of __slots__, for classes with well-defined and fixed fields;
  • Classes cannot be thrown unless they derive from Exception;
  • The MRO (Method Resolution Order) has changed;

Conclusion

In this article we learned why in Python classes we should use the object

Actually we shouldn’t, it’s something totally optional and it will work the same both ways

The big difference is that by declaring it, the argument is explicit, which is considered a good Python practice

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x