Python Class and Object


What is Object-Oriented Programming (OOP) in Python?

Object-Oriented Programming (OOP) is a programming paradigm that organizes code into objects and classes. It helps in creating modular, reusable, and scalable applications.


What is a Class in Python?

A class is a blueprint for creating objects. It defines properties (attributes) and behaviors (methods).

Syntax of a Class:

class ClassName:
    # attributes and methods

What is an Object in Python?

An object is an instance of a class. It holds the actual data and uses the methods defined in the class.

Creating an Object:

obj = ClassName()


Example 1: Simple Python Class and Object

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

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

# Creating an object
s1 = Student("Alice", "A")
s1.display()

Output:

Name: Alice, Grade: A

Explanation

  • __init__() is a constructor that runs automatically when an object is created
  • self refers to the current instance of the class
  • s1 is an object of the Student class


Example 2: Multiple Objects

s2 = Student("Bob", "B")
s3 = Student("Charlie", "A+")
s2.display()
s3.display()

Output:

Name: Bob, Grade: B
Name: Charlie, Grade: A+

Class Variables vs Instance Variables

Instance Variable

Defined inside __init__(), unique to each object.


Class Variable

Shared by all instances.

class Dog:
    species = "Canine"  # Class variable

    def __init__(self, name):
        self.name = name  # Instance variable

d1 = Dog("Buddy")
d2 = Dog("Max")

print(d1.name, d1.species)
print(d2.name, d2.species)

Output:

Buddy Canine
Max Canine


Modifying Object Properties

d1.name = "Charlie"
print(d1.name)

Output:

Charlie

Why Use Classes in Python?

  • Organize code with real-world modeling
  • Promote reusability and DRY (Don't Repeat Yourself) principles
  • Make code more modular and scalable


Real-World Use Case: Bank Account

class BankAccount:
    def __init__(self, holder, balance=0):
        self.holder = holder
        self.balance = balance

    def deposit(self, amount):
        self.balance += amount

    def display(self):
        print(f"{self.holder}'s Balance: ${self.balance}")

acc1 = BankAccount("John", 1000)
acc1.deposit(500)
acc1.display()

Output:

John's Balance: $1500