Class Inheritance
Inheritance allows a class (child) to inherit attributes and methods from another class (parent), promoting code reuse and creating hierarchies.
💻 Basic Inheritance
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return f"{self.name} makes a sound"
class Dog(Animal): # Dog inherits from Animal
def speak(self): # Override parent method
return f"{self.name} barks"
class Cat(Animal):
def speak(self):
return f"{self.name} meows"
dog = Dog("Buddy")
cat = Cat("Whiskers")
print(dog.speak()) # Buddy barks
print(cat.speak()) # Whiskers meows🔧 super() Function
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
class Manager(Employee):
def __init__(self, name, salary, department):
super().__init__(name, salary) # Call parent constructor
self.department = department
manager = Manager("Alice", 80000, "Engineering")
print(f"{manager.name}: ${manager.salary}, {manager.department}")📚 Multiple Inheritance
class Flyable:
def fly(self):
return "Flying high!"
class Swimmable:
def swim(self):
return "Swimming fast!"
class Duck(Flyable, Swimmable):
def quack(self):
return "Quack!"
duck = Duck()
print(duck.fly()) # Flying high!
print(duck.swim()) # Swimming fast!
print(duck.quack()) # Quack!🎯 Key Takeaways
- Inheritance: Child class inherits from parent
- Override: Replace parent methods in child
- super(): Access parent class methods
- Multiple inheritance: Inherit from multiple classes
- isinstance(): Check object type
- issubclass(): Check class relationships