The most important concept to understand based on java background is that class inheritance is a tool that is rarely needed to solve problems in python. The instant word for this idea is duck.
Most python programs access and invoke attributes on an object or another. As in java, you can get useful behavior by providing a function that expects an object of one type to be an object of another, more subtle type. For this to work in java, it is necessary that the replaced object either inherit from the expected type or implement the expected interface.
In python, this is not necessary at all; If the replaced object has all the attributes that you pass to it, then it will work.
The only reason for inheriting in python is that the superclass really, really does pretty much everything you need for the new type, and you only need to add a few extra actions.
The most common example of this is the iterator protocol in python. Any object that has the __iter__() method that returns the object itself, and the next() method that returns anything at all, is an iterator and a for statement may appear. str , list , dict , file and many other types that have nothing in common, and only the global object as a regular superclass, each implements an iterator protocol.
source share