What do you know about inheritance in Python?
sobes.tech AI
Answer from AI
Inheritance in Python is a mechanism that allows one class to inherit attributes and methods from another class. The class that inherits is called the child (subclass), and the class from which inheritance occurs is called the parent (superclass).
Advantages:
- Code reuse: methods and attributes of the parent class can be used in child classes without rewriting.
- Extensibility: child classes can add their own attributes and methods or override (change behavior of) inherited ones.
- Polymorphism: objects of different classes can respond differently to the same method call if the classes are part of an inheritance hierarchy.
Syntax:
class ParentClass:
# Attributes and methods of the parent class
class ChildClass(ParentClass):
# Attributes and methods of the child class
# Can override parent class methods
Overriding methods:
A child class can provide its own implementation of a method that already exists in the parent class. When this method is called on an object of the child class, the child's version will be executed.
class Animal:
def speak(self):
pass
class Dog(Animal):
def speak(self):
return "Woof!"
class Cat(Animal):
def speak(self):
return "Meow!"
Calling parent class methods:
Sometimes, in an overridden method of a child class, it is necessary to execute the code of the parent method. For this, the super() function is used.
class Parent:
def method(self):
print("Parent class method")
class Child(Parent):
def method(self):
super().method() # Call parent class method
print("Child class method")
Multiple inheritance:
Python supports multiple inheritance, where a class can inherit from multiple classes.
class Class1:
pass
class Class2:
pass
class ChildClass(Class1, Class2):
pass
In multiple inheritance, it is important to consider the Method Resolution Order (MRO), which determines the order in which methods are searched in the class hierarchy. It can be viewed using the __mro__ attribute.
Example of inheritance hierarchy:
# Base class
class Shape:
def __init__(self, name="Shape"):
self.name = name
def area(self):
raise NotImplementedError("Subclasses must implement this method")
# Child class
class Rectangle(Shape):
def __init__(self, width, height):
super().__init__("Rectangle") # Call parent constructor
self.width = width
self.height = height
def area(self):
return self.width * self.height
# Another child class
class Circle(Shape):
def __init__(self, radius):
super().__init__("Circle")
self.radius = radius
def area(self):
return 3.14 * self.radius**2
# Usage
rectangle = Rectangle(10, 5)
circle = Circle(7)
print(f"{rectangle.name} area: {rectangle.area()}")
print(f"{circle.name} area: {circle.area()}")