
🐍 Lesson 2: Classes & Objects
1. What is a class?
In short → A class is a blueprint that gives you the foundation for creating objects.
In detail → A class is a blueprint for creating objects. It defines attributes (data) and methods (functions).
2. What is an object?
In short → An object is an instance created from a class, representing real, usable data + behavior.
In detail → An object is an instance of a class. It represents actual data and behavior defined by the class.
3. Summary
✅ Class = blueprint, Object = instance
✅ __init__ = constructor for initialization
✅ Attributes = variables, Methods = functions inside class
✅ OOP makes code modular, reusable, and closer to real-world modeling
python
# ===== 1. Basic Syntax =====
class Person:
def __init__(self, name, age): # Constructor
self.name = name # Attribute
self.age = age
def greet(self): # Method
return f"Hello, my name is {self.name} and I am {self.age} years old."
# ===== 2. Create Objects =====
p1 = Person("Sai", 25)
p2 = Person("Aye", 30)
print(p1.greet()) # Hello, my name is Sai and I am 25 years old.
print(p2.greet()) # Hello, my name is Aye and I am 30 years old.
# ===== 3. Multiple Objects =====
dog1 = Person("Bobby", 5)
dog2 = Person("Lucky", 3)
print(f"\ndog1.name = {dog1.name}") # Bobby
print(f"dog2.age = {dog2.age}") # 3
# ===== 4. Real-World Analogy =====
print(f"\n===== Analogy =====")
print("Class = Car blueprint")
print("Object = Actual car (Toyota, Honda)")
print("Attributes = color, model, year")
print("Methods = drive(), stop(), honk()")You should see
Hello, my name is Sai and I am 25 years old. Hello, my name is Aye and I am 30 years old. dog1.name = Bobby dog2.age = 3 ===== Analogy ===== Class = Car blueprint Object = Actual car (Toyota, Honda) Attributes = color, model, year Methods = drive(), stop(), honk()