Inheritance
Since Python is an OOP language, it supports inheritance. Inheritance is a mechanism by which one class
(also known as a child class) is allowed to keep or override the variables and methods declared in another class (also known as a parent class).
Inheritance allows us to create a hierarchy among classes to help organize classes in a meaningful way.
In Python you can inherit a class by using the name of the class inside a pair of parenthesis in the first line of the class definition. Here is an example:
class Animal:
def speak(self):
print('Every animal speaks in its own way')
class Dog(Animal):
pass
animal = Animal()
animal.speak()
dog = Dog()
dog.speak()
Output:
Every animal speaks in its own way
Every animal speaks in its own way
In the above example, we created an 'Animal' class that has a speak method. We also declared a class called 'Dog' that inherits the 'Animal' class. The Dog class is empty, but since it inherits the Animal class, it can invoke the speak method of the Animal class.
When we instantiate the Dog class, we can use the 'speak()' method defined in the Animal class.
Overriding
However, a dog does speak in one way: "woof woof". So let us override the inherited method from the Animal class and provide an implementation for speak that is appropriate for a Dog.
class Animal:
def speak(self):
print('Every animal speaks in its own way')
class Dog(Animal):
def speak(self):
print('Woof Woof')
animal = Animal()
animal.speak()
dog = Dog()
dog.speak()
Output:
Every animal speaks in its own way
Woof Woof
Now do you see how the dog instance is no longer using the inherited method but is using the overridden method in the Dog class?
isinstance, issubclass methods
You can find if an instance object is of a specific type by using the isinstance() built-in function
isinstance(dog, Dog) --> returns True
On the same lines you can also find if a class type is a subclass of another class
issubclass(Dog, Animal) --> returns True
Multiple inheritances
Python supports multiple inheritance. You just have to enclose all the parent class names inside the parentheses, separated by a comma
class Dog(Mammal, Animal):
pass
Other Concepts
Overloading: If you are coming from Java background then there is no concept of overloading a method in Python. A method definition is replaced with the last one defined with the same name. Variations in the argument list do not matter.
Private variables: Python doesn’t have true private variables like in some other languages. However, by convention, if you prefix an attribute name with double underscores (e.g., __my_variable), Python will change its name to make it harder to access from outside the class. This is called name mangling.