Python Inheritance 👪
Parent and Child Classes
Inheritance allows us to define a class that inherits all the methods and properties from another class. The Parent class is the class being inherited from (base class). The Child class is the class that inherits from another class (derived class).
🧬 Analogy: DNA
Think of inheritance like biological DNA.
- You (Child Class) inherit traits like eye color and height from your parents (Parent Class).
- You automatically have these traits without doing anything.
- But you can also learn new skills (New Methods) or dye your hair (Override Methods) to be unique!
✨ The super() Function
Python has a super() function that will make the child class inherit all the methods and properties from its parent. This is preferred over calling the parent name directly.
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
class Student(Person):
def __init__(self, fname, lname, year):
super().__init__(fname, lname)
self.graduationyear = year
def welcome(self):
print("Welcome", self.firstname, self.lastname, "to the class of", self.graduationyear)
x = Student("Mike", "Olsen", 2019)
x.welcome()🎯 Real-World Application: UI Components
In GUI programming (like React or Tkinter), everything is a component.
class UIComponent:
def render(self):
print("Rendering generic component...")
class Button(UIComponent):
def render(self):
print("Rendering a clickable BUTTON!")
class TextBox(UIComponent):
def render(self):
print("Rendering a text input box...")
# They all share common traits but behave differently
components = [Button(), TextBox()]
for c in components:
c.render()🌳 Multiple Inheritance
Python supports multiple inheritance, where a class can inherit from multiple parent classes.
class A:
def method_a(self):
print("Method A")
class B:
def method_b(self):
print("Method B")
class C(A, B):
def method_c(self):
print("Method C")
obj = C()
obj.method_a()
obj.method_b()
obj.method_c()⚠️ Method Resolution Order (MRO)
When using multiple inheritance, Python uses MRO to determine which method to call. It generally searches depth-first, left-to-right. You can check the order using ClassName.mro().