Inheritance in Python
What is Inheritance? Inheritance allows a class (called the child class or subclass) to inherit properties and methods from another class (called the parent class or superclass).
✅ Purpose: It promotes code reusability and logical hierarchy among classes.
Basic Syntax
class ParentClass:
# parent class code
pass
class ChildClass(ParentClass):
# child class code
Pass The ChildClass inherits all the attributes and methods from ParentClass.
Example: Basic Inheritance.
Python
# Parent class
class Animal:
def speak(self):
print("Animals make sounds")
# Child class inherits from Animal
class Dog(Animal):
def bark(self):
print("Dog barks")
# Create object of Dog
d = Dog()
# Access methods
d.speak() # Inherited from Animal
d.bark() # Defined in Dog Output: Animals make sounds
Dog barks
Explanation: • Dog inherits from Animal.
• So, Dog objects can use both speak() and bark() methods.