Python Inheritance
Extend classes using inheritance.
Reuse code with inheritance.
Basic Inheritance
```python class Animal: def __init__(self, name): self.name = name def speak(self): print("Some sound")
class Dog(Animal): def speak(self): print(f"{self.name} says Woof!")
class Cat(Animal): def speak(self): print(f"{self.name} says Meow!")
dog = Dog("Max") cat = Cat("Whiskers")
dog.speak() # Max says Woof! cat.speak() # Whiskers says Meow! ```
Using super()
```python class Vehicle: def __init__(self, brand): self.brand = brand def info(self): print(f"Brand: {self.brand}")
class Car(Vehicle): def __init__(self, brand, model): super().__init__(brand) self.model = model def info(self): super().info() print(f"Model: {self.model}")
car = Car("Tesla", "Model 3") car.info() # Brand: Tesla # Model: Model 3 ```
Multiple Inheritance
```python class Walker: def walk(self): print("Walking...")
class Swimmer: def swim(self): print("Swimming...")
class Duck(Walker, Swimmer): pass
duck = Duck() duck.walk() # Walking... duck.swim() # Swimming... ```
Remember
- Child class inherits parent methods - Use super() to call parent methods - Override methods when needed