I've been using Python for quite a while now, and I'm still unsure as to why you would subclass from object
. What is the difference between this:
class MyClass():
pass
And this:
class MyClass(object):
pass
As far as I understand, object
is the base class for all classes and the subclassing is implied. Do you get anything from explicitly subclassing from it? What is the most "Pythonic" thing to do?
In inheritance, a class (usually called superclass) is inherited by another class (usually called subclass). The subclass adds some attributes to superclass. Below is a sample Python program to show how inheritance is implemented in Python. # Base or Super class.
Inheritance is a required feature of every object oriented programming language. This means that Python supports inheritance, and as you'll see later, it's one of the few languages that supports multiple inheritance.
You don't need to inherit from object to have new style in python 3. All classes are new-style.
All the Python built-ins are subclasses of object and I come across many user-defined classes which are too.
This is oldstyle and new style classes in python 2.x. The second form is the up to date version and exist from python 2.2 and above. For new code you should only use new style classes.
In Python 3.x you can again use both form indifferently as the new style is the only one left and both form are truly equivalent. However I believe you should continue to use the MyClass(object)
form even for 3.x code at least until python 3.x is widely adopted to avoid any misunderstanding with potential readers of your code used to 2.x.
Behavior between old style and new style classes is very different regarding to certain features like use of super().
See here : New Style classes
You can also see here on SO.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With