Inheritance
Inheritance is a fundamental OOP concept allowing a new class (the child or subclass) to derive or inherit attributes and methods from an existing class (the parent or superclass).
Syntax
Specify the parent class in parentheses when defining the child class.
python class Animal: # Parent/Superclass def init(self, name): self.name = name
def speak(self):
raise NotImplementedError("Subclass must implement abstract method")
class Dog(Animal): # Child/Subclass inherits from Animal def speak(self): return f"{self.name} says Woof!"
class Cat(Animal): def speak(self): return f"{self.name} says Meow."
Instances of subclasses
fido = Dog('Fido') luna = Cat('Luna')
print(fido.name) # Fido (Inherited attribute) print(fido.speak()) # Fido says Woof! print(luna.speak()) # Luna says Meow.
Benefits
- Code Reusability: Methods in the parent class are instantly available to all children.
- Structure: Creates a clear hierarchy (e.g., Dog IS-A Animal).