Python OOPs: Class, Object, Inheritance and Constructor with Example

Created with Sketch.

Object-oriented programming (OOP) is a paradigm that uses objects to structure code. In Python, you can create classes and objects to implement OOP concepts. Here’s a basic example that covers class creation, object instantiation, inheritance, and the use of constructors:

1. Creating a Class and Instantiating Objects:

 
class Animal:
    def __init__(self, name, species):
        self.name = name
        self.species = species

    def make_sound(self):
        pass  # Placeholder method to be overridden by subclasses

# Instantiate objects of the Animal class
cat = Animal("Whiskers", "Cat")
dog = Animal("Buddy", "Dog")

# Accessing attributes and methods of objects
print(f"{cat.name} is a {cat.species}.")
print(f"{dog.name} is a {dog.species}.")

In this example, we have created a basic Animal class with an __init__ method (constructor) to initialize the object’s attributes (name and species). The make_sound method is a placeholder that can be overridden by subclasses.

2. Inheritance:

class Cat(Animal):
    def make_sound(self):
        return "Meow!"

class Dog(Animal):
    def make_sound(self):
        return "Woof!"

# Instantiate objects of the derived classes
fluffy = Cat("Fluffy", "Persian Cat")
buddy = Dog("Buddy", "Golden Retriever")

# Accessing overridden methods
print(f"{fluffy.name} says: {fluffy.make_sound()}")
print(f"{buddy.name} says: {buddy.make_sound()}")

In this example, Cat and Dog are subclasses of the Animal class, and they override the make_sound method to provide specific behavior for each type of animal.

3. Constructor:

The __init__ method is a constructor that initializes the object’s attributes when it is created. Here’s an example with a constructor:

class Student:
    def __init__(self, name, age, grade):
        self.name = name
        self.age = age
        self.grade = grade

    def display_info(self):
        print(f"Name: {self.name}, Age: {self.age}, Grade: {self.grade}")

# Instantiate objects of the Student class using the constructor
student1 = Student("Alice", 16, "A")
student2 = Student("Bob", 17, "B")

# Accessing attributes and methods
student1.display_info()
student2.display_info()

In this example, the Student class has a constructor that initializes the name, age, and grade attributes. The display_info method prints information about the student.

These examples provide a basic understanding of classes, objects, inheritance, and constructors in Python’s OOP paradigm. You can extend and modify these concepts based on the specific requirements of your application.

Leave a Reply

Your email address will not be published. Required fields are marked *