Day 7: Object-Oriented Programming (OOP) in Python: Class and Objects

·

2 min read

Introduction

Object-Oriented Programming (OOP) is a programming paradigm that allows developers to structure their code using objects and classes. Python, being an object-oriented language, makes it easy to work with OOP principles.

What is a Class?

A class is a blueprint or template for creating objects. It defines the attributes (variables) and methods (functions) that objects of that class will have.

Defining a Class

In Python, a class is defined using the class keyword.

Here, Car is a class, but it does not contain any attributes or methods yet.

class Student:
    pass  # An empty class (for now)

What is an Object?

An object is an instance of a class. It represents a real-world entity and contains data (attributes) and behaviors (methods).

Creating an Object

Once a class is defined, we can create objects from it.

#creating class
class Student:
    name = "John Doe"
#creating object - instance
s1 = Student()
print(s1.name)

Constructors

A constructor is a special method in Python (__init__) that is automatically called when an object is created. It initializes the object’s attributes.

Types of Constructors:

  1. Default Constructor

  2. Parameterized Constructor

Default Constructor

A default constructor does not take any parameters except self. It initializes attributes with default values.

class Student:
    name = "Sravya"
    #default constructor
    def __init__(self):
        print("hello")
        self.name = "Sravya"

s1 = Student()
print(s1.name)

#output
#hello
#Sravya

Parameterized Constructor

A parameterized constructor accepts arguments and initializes attributes dynamically.

class Student:
    name = "Rishitha"
    #parameterized constructor
    def __init__(self, name, id, marks):
        self.name = name
        self.id = id
        self.marks = marks

s1 = Student("Rishitha", 101, 97)
print(s1.name, s1.id, s1.marks)

s2 = Student("Sravya", 102, 89)
print(s2.name, s2.id, s2.marks)

#Output
#Rishitha 101 97
#Sravya 102 89