Parent and child classes help organize code by sharing common features. The child class can use or change what the parent class has.
0
0
Parent and child classes in Python
Introduction
When you want to create a new type that is similar to an existing one but with some changes.
When you want to reuse code from a general class to avoid repeating yourself.
When you want to group related objects that share common behavior.
When you want to add new features to an existing class without changing it.
When you want to create a clear relationship between general and specific things.
Syntax
Python
class ParentClass: def __init__(self, value): self.value = value class ChildClass(ParentClass): def __init__(self, value, extra): super().__init__(value) self.extra = extra
The child class name is followed by parentheses containing the parent class name.
Use super() to call the parent class's methods inside the child class.
Examples
The
Dog class inherits from Animal and changes the speak method.Python
class Animal: def speak(self): print("Animal speaks") class Dog(Animal): def speak(self): print("Dog barks")
The
Car class adds a new property model but keeps brand from Vehicle.Python
class Vehicle: def __init__(self, brand): self.brand = brand class Car(Vehicle): def __init__(self, brand, model): super().__init__(brand) self.model = model
Sample Program
This program shows a parent class Person and a child class Student. The child class adds a student ID and changes the greeting.
Python
class Person: def __init__(self, name): self.name = name def greet(self): print(f"Hello, my name is {self.name}.") class Student(Person): def __init__(self, name, student_id): super().__init__(name) self.student_id = student_id def greet(self): print(f"Hi, I'm {self.name} and my student ID is {self.student_id}.") p = Person("Alice") p.greet() s = Student("Bob", "S12345") s.greet()
OutputSuccess
Important Notes
If the child class does not have a method, it uses the parent's method automatically.
You can add new methods or properties in the child class that the parent does not have.
Summary
Parent classes hold common features for child classes.
Child classes inherit and can change or add features.
Use super() to access parent class methods inside child classes.