Inheritance is the process of getting the features from a base class to the derived class.
when you are defining the derived class make sure the base class name is in the scope.
class DerivedClass(modname.BaseClass):
<Statement 1>
.
.
<Statement n>
When the base class you want to inherit is in another module you use its module name to use.
When an object is created for the derived class and looking for an attribute first python looks into the DerivedClass and then into the BaseClass.
Derived classes may override methods of their base classes. Because methods have no special privileges when calling other methods of the same object, a method of a base class that calls another method defined in the same base class may end up calling a method of a derived class that overrides it. (For C++ programmers: all methods in Python are effectively
virtual
.)An overriding method in a derived class may, in fact, want to extend rather than simply replace the base class method of the same name. There is a simple way to call the base class method directly just call:
BaseClass.method(self, arguments)
Python has two built-in functions that work with inheritance :
1) isinstance( )
This method is used to check an instance type: suppose isinstance(obj,int)
It returns true if obj is the object of the class int or obj.__class__ is int.
2) issubclass( )
This method is used to check the class inheritance: suppose
issubclass(bool, int). It returns true if bool is a subclass of int. Which is true.
Python also supports multiple inheritances. Which means it has two or more base classes. you can think of the search for attributes inherited from a parent class as depth-first, left-to-right, not searching twice in the same class where there is an overlap in the hierarchy.
In a class hierarchy with single inheritance, super can be used to refer to parent classes without naming them explicitly, thus making the code more maintainable. This use closely parallels the use of super in other programming languages.
The second use case is to support cooperative multiple inheritances in a dynamic execution environment. This use case is unique to Python and is not found in statically compiled languages or languages that only support single inheritance. This makes it possible to implement “diamond diagrams” where multiple base classes implement the same method. Good design dictates that this method has the same calling signature in every case.
Dynamic ordering is necessary because all cases of multiple inheritances provide one or more diamond relationships. To keep the base classes from being accessed more than once, the dynamic algorithm linearizes the search order in a way that preserves the left-to-right ordering specified in each class, that calls each parent only once, and that is monotonic.
No comments