Understanding Classes in Object-Oriented Programming
Page 1: What is a Class?
In object-oriented programming (OOP), a class is a model or blueprint for creating objects.
It defines the structure and behavior that the created objects (instances) will have.
Real-Life Analogy:
Think of a 'Mobile Phone' class. All phones have common features like screen size, battery,
and camera. Each actual mobile phone you use is an object of the 'Mobile Phone' class.
Essential Parts of a Class:
- Attributes: Data stored inside an object (e.g., brand, price)
- Methods: Functions that operate on object data (e.g., call(), take_photo())
Python Class Example:
class MobilePhone:
def __init__(self, brand, price):
self.brand = brand
self.price = price
def call(self):
print("Calling...")
This defines a class `MobilePhone` with attributes and a method.
Page 2: Why Classes Matter
Benefits of Using Classes:
1. Modularity: Keep code pieces independent and manageable.
2. Code Reusability: Use the same class multiple times to create different objects.
3. Maintainability: Easier to update and maintain.
4. Security: Hide the internal state of objects using encapsulation.
Creating an Object from Class:
phone1 = MobilePhone("Samsung", 15000)
phone1.call()
Another Class Example: Book
class Book:
def __init__(self, title, author):
self.title = title
self.author = author
def display(self):
print("Title:", self.title)
print("Author:", self.author)
b1 = Book("Python Basics", "Neha")
b1.display()
Conclusion:
Classes make programming easier and more structured. They are used in all major OOP
languages such as Python, C++, and Java.