Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would it be necessary to subclass from object in Python?

Tags:

python

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?

like image 463
rmh Avatar asked Apr 26 '10 16:04

rmh


People also ask

What is the purpose of subclasses in Python?

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.

Should I inherit from object in Python?

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.

Do you need to inherit from object Python 3?

You don't need to inherit from object to have new style in python 3. All classes are new-style.

Are all Python classes subclasses of object?

All the Python built-ins are subclasses of object and I come across many user-defined classes which are too.


1 Answers

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.

like image 190
kriss Avatar answered Oct 14 '22 11:10

kriss