Python Notes
Master the foundation of Object-Oriented Programming — learn how to define classes, create objects, use attributes and methods, and understand how Python models real-world entities as code.
🧠 Real-World Analogy — Blueprint aur Building
Think of an architect's blueprint — it's a design that specifies what the building will look like: how many floors, how many rooms, where the doors are. When a contractor builds an actual building from that blueprint — that's an object. From one blueprint, you can build thousands of different buildings — each with its own location, color, and address.
In Python:
- Class = Blueprint (design / template)
- Object = Actual instance built from that blueprint
📐 ASCII Class Diagram
+---------------------------+
| Car | ← Class Name
+---------------------------+
| - make: str | ← Attributes (data)
| - model: str |
| - year: int |
| - speed: float |
+---------------------------+
| + start() | ← Methods (behavior)
| + accelerate(amount) |
| + brake() |
| + get_info() -> str |
+---------------------------+🚗 Example 1 — Defining a Class and Creating Objects
Output:
🔍 Understanding self
selfmeans "this object itself". When you callcar1.start(), Python automatically passescar1asself.
# These two calls are IDENTICAL:
car1.start() # ← short form (Python sugar)
Car.start(car1) # ← explicit form (shows what really happens)self is NOT a keyword — it is a convention. You could name it anything, but always use self.
🏗️ Class Variables vs Instance Variables
class Student:
school_name = "WoHoTech Academy" # ← class variable (shared)
def __init__(self, name, grade):
self.name = name # ← instance variable (unique)
self.grade = grade
def introduce(self):
print(f"Hi, I'm {self.name}, grade {self.grade} at {Student.school_name}")
s1 = Student("Arjun", 10)
s2 = Student("Priya", 11)
s1.introduce()
s2.introduce()
# Changing class variable affects ALL instances
Student.school_name = "WoHoTech Global Academy"
s1.introduce() # updated!
s2.introduce() # updated!
# Changing instance variable affects ONLY that instance
s1.name = "Arjun Kumar"
print(s1.name) # Arjun Kumar
print(s2.name) # Priya (unchanged)Output:
🏦 Example 2 — Bank Account
class BankAccount:
bank_name = "WoHo National Bank"
interest_rate = 0.04 # 4% annual
def __init__(self, owner, balance=0):
self.owner = owner
self._balance = balance # convention: _ means "protected"
self.transactions = []
def deposit(self, amount):
if amount <= 0:
print("❌ Deposit amount must be positive.")
return
self._balance += amount
self.transactions.append(f"+₹{amount}")
print(f"✅ Deposited ₹{amount}. New balance: ₹{self._balance}")
def withdraw(self, amount):
if amount > self._balance:
print(f"❌ Insufficient funds. Balance: ₹{self._balance}")
return
self._balance -= amount
self.transactions.append(f"-₹{amount}")
print(f"✅ Withdrew ₹{amount}. New balance: ₹{self._balance}")
def get_balance(self):
return self._balance
def add_interest(self):
interest = self._balance * BankAccount.interest_rate
self._balance += interest
print(f"💰 Interest added: ₹{interest:.2f}. New balance: ₹{self._balance:.2f}")
def statement(self):
print(f"\n{'='*40}")
print(f" {BankAccount.bank_name}")
print(f" Account holder: {self.owner}")
print(f" Balance: ₹{self._balance}")
print(f" Transactions: {', '.join(self.transactions)}")
print(f"{'='*40}\n")
acc1 = BankAccount("Rahul Sharma", 10000)
acc2 = BankAccount("Sneha Gupta", 5000)
acc1.deposit(2000)
acc1.withdraw(500)
acc1.add_interest()
acc1.statement()
acc2.withdraw(6000) # should fail
acc2.deposit(1000)
acc2.statement()Output:
| ✅ Deposited ₹2000. New balance | ₹12000 |
| ✅ Withdrew ₹500. New balance | ₹11500 |
| 💰 Interest added | ₹460.00. New balance: ₹11960.00 |
| Account holder | Rahul Sharma |
| Balance | ₹11960.0 |
| Transactions | +₹2000, -₹500 |
| ❌ Insufficient funds. Balance | ₹5000 |
| ✅ Deposited ₹1000. New balance | ₹6000 |
| Account holder | Sneha Gupta |
| Balance | ₹6000 |
| Transactions | +₹1000 |
📦 Example 3 — Product Inventory
Output:
| [PRD-1000] Python Book | Price | ₹ 599.00 | Qty: 50 |
| [PRD-1001] USB-C Cable | Price | ₹ 299.00 | Qty: 120 |
| [PRD-1002] Laptop Stand | Price | ₹ 1499.00 | Qty: 30 |
| [PRD-1003] Mechanical Keyboard | Price | ₹ 3499.00 | Qty: 15 |
| Restocked 20 units of 'Laptop Stand'. Total | 50 |
| [PRD-1000] Python Book | Price | ₹ 599.00 | Qty: 40 |
| [PRD-1001] USB-C Cable | Price | ₹ 299.00 | Qty: 120 |
| [PRD-1002] Laptop Stand | Price | ₹ 1499.00 | Qty: 50 |
| [PRD-1003] Mechanical Keyboard | Price | ₹ 3499.00 | Qty: 15 |
| Total inventory value | ₹1,37,745.00 |
🔬 Object Identity, Equality and Type
car1 = Car("Toyota", "Camry", 2022)
car2 = Car("Toyota", "Camry", 2022)
car3 = car1 # same reference!
# Identity (same object in memory?)
print(car1 is car3) # True — same reference
print(car1 is car2) # False — different objects
# id() returns memory address
print(id(car1))
print(id(car2))
print(id(car3)) # same as car1
# Type checking
print(type(car1)) # <class '__main__.Car'>
print(isinstance(car1, Car)) # True🧩 Deleting Objects and Attributes
car1 = Car("Toyota", "Camry", 2022)
# Delete an attribute
del car1.speed
# print(car1.speed) # AttributeError!
# Delete the object reference
del car1
# print(car1) # NameError!del only deletes the reference. The actual object is garbage collected when no references remain.📊 Summary Table
| Concept | Description | Example |
|---|---|---|
| Class | Blueprint / template | class Car: |
| Object | Instance of class | car1 = Car(...) |
| Attribute | Data stored in object | car1.speed |
| Method | Function inside class | car1.start() |
self | Reference to current instance | self.name |
| Class var | Shared across all instances | Car.total_cars |
| Instance var | Unique per object | self.model |
🇮🇳 Hindi Explanation (हिंदी में समझें)
Class kya hai? A class is a template or blueprint that defines what data (attributes) an object will have and what it can do (methods).
Object kya hai? An object is a specific instance of a class — like multiple different items made from the same mold.
selfkyon zaroori hai?selfis used so that a method knows which specific object it's working on.
Class variable aur instance variable mein farq? A class variable is common across all instances (like a school's name), while an instance variable is unique to each object (like a student's name).
❓ Interview Questions
Q1: What is the difference between a class and an object?
Answer: A class is a blueprint or template that defines attributes and behaviors. An object is a concrete instance created from that class. You can create many objects from a single class, each with its own independent state.
Q2: What is self in Python? Is it a keyword?
Answer: self is a reference to the current instance of the class. It is not a Python keyword — it is a strong convention. When you call obj.method(), Python automatically passes the object as the first argument (self). You could technically name it anything, but self is universally used.
Q3: Difference between class variable and instance variable?
Answer:
- Class variable: defined at class level, shared by all instances. Changing it affects all objects (unless overridden on the instance).
- Instance variable: defined inside
__init__usingself, unique to each object.
class Demo:
class_var = "shared" # class variable
def __init__(self):
self.instance_var = "unique" # instance variableQ4: How does Python garbage collect objects?
Answer: Python uses reference counting. When an object's reference count drops to zero (no variable points to it), it is immediately deallocated. The gc module handles cyclic references that reference counting alone cannot resolve.
Q5: Can you add attributes to an object outside the class definition?
Answer: Yes. Python allows dynamic attribute assignment:
car1 = Car("Toyota", "Camry", 2022)
car1.color = "Red" # added dynamically
print(car1.color) # RedThis is generally discouraged in production code — prefer defining all attributes in __init__.
Q6: What is the difference between type() and isinstance()?
Answer:
type(obj) == Carchecks exact type — returnsFalsefor subclasses.isinstance(obj, Car)returnsTruefor the class and any subclass — preferred for type checking in OOP.
Q7: What happens when you call del obj?
Answer: del obj removes the name binding (reference), not the object itself. The object is garbage collected only when its reference count reaches zero (i.e., no other name or data structure holds a reference to it).
🧪 Practice Exercises
- Library Book: Create a
Bookclass withtitle,author,isbn,copies_available. Addcheckout()andreturn_book()methods. - Temperature: Create a
Temperatureclass that stores value in Celsius. Add methodsto_fahrenheit()andto_kelvin(). - Circle: Create a
Circleclass withradius. Addarea(),circumference(), andis_unit_circle()methods. - Counter: Create a
Counterclass withincrement(),decrement(),reset(), andvalueproperty. Track a class-leveltotal_operationscounter. - Student Report: Create a
Studentclass that stores marks in 5 subjects. Addtotal(),average(),grade(), andis_pass()methods.
💡 Next Topic → Constructors: Dive deep into__init__, default arguments, class methods as alternate constructors, and__del__.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Classes and Objects in Python.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Python Master Course topic.
Search Terms
python-master-course, python master course, python, master, course, object, oriented, programming
Related Python Master Course Topics