0
0
Pythonprogramming~5 mins

Inheriting attributes and methods in Python

Choose your learning style9 modes available
Introduction

Inheritance lets one class use features from another class. It helps avoid repeating code and makes programs easier to manage.

When you want a new class to have the same features as an existing class but also add new ones.
When you want to organize related classes in a family tree style.
When you want to reuse code from a class without copying it.
When you want to create a general class and more specific classes based on it.
Syntax
Python
class ParentClass:
    def method(self):
        pass

class ChildClass(ParentClass):
    pass

The child class name is followed by parentheses containing the parent class name.

The child class automatically gets all methods and attributes of the parent.

Examples
Dog inherits speak() from Animal, so Dog can use it without extra code.
Python
class Animal:
    def speak(self):
        print("Animal sound")

class Dog(Animal):
    pass
Cat changes the speak() method to make its own sound, replacing the parent method.
Python
class Animal:
    def speak(self):
        print("Animal sound")

class Cat(Animal):
    def speak(self):
        print("Meow")
Sample Program

This program shows a Car class inheriting from Vehicle. Car gets the brand attribute and honk() method from Vehicle. It also has its own drive() method.

Python
class Vehicle:
    def __init__(self, brand):
        self.brand = brand
    def honk(self):
        print(f"{self.brand} goes beep beep!")

class Car(Vehicle):
    def drive(self):
        print(f"{self.brand} is driving")

my_car = Car("Toyota")
my_car.honk()
my_car.drive()
OutputSuccess
Important Notes

If the child class has a method with the same name as the parent, it replaces the parent's method.

You can call the parent method inside the child method using super().

Inheritance helps keep code clean and organized by sharing common features.

Summary

Inheritance lets a class use attributes and methods from another class.

Child classes get all features of parent classes automatically.

You can add or change features in the child class as needed.