File handling and object oriented Python notes — Unit 4
Free unit-wise study notes on file handling and object oriented python for Python Programming, Semester 3 of B.Tech — Computer Science & Engineering — key concepts, examples, important questions and a revision checklist for semester exams.
Persistent storage and software architecture. Covers reading/writing files, CSV handling, the `with` statement, and the pillars of OOP: Classes, Objects, `__init__`, Inheritance, and Polymorphism.
Notebook — 14 pages
Page 1
Wink Notes
B.Tech CSE — 3rd Semester
Python Programming
— Unit - 4 —
1. File Handling Basics
Variables in RAM are lost when a program closes. To store data permanently (persistence), we must save it to a File on the Hard Drive.
⇒1.1 The `open()` Function
To interact with a file, you must first open it. The `open()` function returns a File Object.
`file = open("data.txt", "r")`
⇒1.2 Access Modes
`"r"` (Read): Default. Opens for reading. Crashes if file doesn't exist.
`"w"` (Write): Opens for writing. Erases the file completely if it exists. Creates it if it doesn't.
`"a"` (Append): Opens for writing. Appends new data to the end of the file without erasing existing data.
`"r+"` / `"w+"`: Opens for both reading and writing.
`"b"`: Appended for binary files (e.g., `"rb"` to read an image).
Page 2
Wink Notes
B.Tech CSE — 3rd Semester
Python Programming
— Unit - 4 —
2. Reading and Writing
⇒2.1 Writing to a File
Use the `write()` method. Note that `write()` does NOT automatically add a newline at the end; you must include `\n` manually.
```python f = open("log.txt", "w") f.write("System Booted\n") f.close() # CRITICAL: You must close the file to save it! ```
⇒2.2 Reading from a File
`f.read()`: Reads the entire file as one giant string.
`f.readline()`: Reads exactly one line. Calling it again reads the next line.
`f.readlines()`: Reads all lines and returns a List of strings.
The most memory-efficient way to read a massive file is to iterate over the file object directly:
```python f = open("big_data.txt", "r") for line in f: print(line) f.close() ```
Page 3
Wink Notes
B.Tech CSE — 3rd Semester
Python Programming
— Unit - 4 —
3. Context Managers: The `with` Statement
Forgetting to call `f.close()` is a common and dangerous bug. It causes memory leaks and can corrupt the file. If an exception occurs before `f.close()` is reached, the file remains open.
⇒3.1 The Solution
Python provides the `with` statement (a Context Manager). It automatically closes the file the moment the indented block ends, even if the program crashes with an exception inside the block.
```python with open("data.txt", "r") as f: content = f.read() print(content) # The file is already safely closed here. ```
This is the industry-standard, "Pythonic" way to handle files.
Page 4
Wink Notes
B.Tech CSE — 3rd Semester
Python Programming
— Unit - 4 —
4. Handling CSV Files
Comma-Separated Values (CSV) is the most common format for tabular data (like Excel sheets). Python has a built-in `csv` module to handle them effortlessly.
⇒4.1 Reading a CSV
```python import csv
with open("students.csv", "r") as file: reader = csv.reader(file) for row in reader: print(row) # row is a List: ['Alice', '20', 'A'] ```
⇒4.2 Writing a CSV
```python import csv
data = [["Name", "Age"], ["Alice", 20], ["Bob", 22]]
with open("output.csv", "w", newline='') as file: writer = csv.writer(file) writer.writerows(data) ```
Page 5
Wink Notes
B.Tech CSE — 3rd Semester
Python Programming
— Unit - 4 —
5. Object-Oriented Programming (OOP)
OOP is a programming paradigm where software design is centered around data, or objects, rather than functions and logic. It models real-world entities.
⇒5.1 Classes vs. Objects
Class: A blueprint, template, or architectural plan. It defines what attributes (data/variables) and methods (functions/behaviors) a certain type of entity should have. e.g., A `Car` class.
Object (Instance): An actual, concrete entity built from the Class blueprint. Occupies memory. e.g., A specific red Toyota Camry.
You can create hundreds of Objects from a single Class.
Page 6
Wink Notes
B.Tech CSE — 3rd Semester
Python Programming
— Unit - 4 —
6. Classes and `__init__`
⇒6.1 Defining a Class
Classes are defined using the `class` keyword. Class names use PascalCase by convention.
```python class Dog: # The Constructor Method def __init__(self, name, breed): self.name = name self.breed = breed
# An Instance Method def bark(self): print(self.name, "says Woof!") ```
⇒6.2 The `__init__` Method
This is the Constructor. It is automatically executed the exact moment a new Object is created. It is used to initialize the object's attributes.
(The double underscores `__` indicate it's a special "Dunder" or "Magic" method internal to Python).
Page 7
Wink Notes
B.Tech CSE — 3rd Semester
Python Programming
— Unit - 4 —
7. The `self` Parameter
In C++ or Java, `this` is a hidden keyword. In Python, `self` must be explicitly written as the first parameter of every instance method within a class.
⇒7.1 What is it?
`self` represents the specific object that is calling the method. Because hundreds of Dog objects share the same `bark()` code, `self` tells Python which dog is barking.
dog1.bark() # Python implicitly passes dog1 as 'self' ```
When you type `self.name = name`, you are taking the argument passed to the function and attaching it permanently to the object itself.
Page 8
Wink Notes
B.Tech CSE — 3rd Semester
Python Programming
— Unit - 4 —
8. Class vs. Instance Variables
Not all data belongs to an individual object. Some data belongs to the Class as a whole.
⇒8.1 Instance Variables
Defined inside `__init__` using `self.`. Every object has its own independent copy. If Dog A changes its name, Dog B's name is unaffected.
⇒8.2 Class Variables
Defined directly inside the Class, outside any methods. This variable is shared across all objects of that class.
```python class Dog: species = "Canine" # Class variable
def __init__(self, name): self.name = name # Instance variable
print(Dog.species) # Accessed via the Class itself ```
Page 9
Wink Notes
B.Tech CSE — 3rd Semester
Python Programming
— Unit - 4 —
9. Encapsulation
Encapsulation is the concept of wrapping data and the methods that operate on that data within one unit (the object), and restricting outside access to internal state.
Python does NOT have strict `public`, `private`, or `protected` keywords like Java. It relies on naming conventions.
⇒9.1 Name Mangling (Pseudo-Private)
Public: `self.name`. Accessible anywhere.
Protected: `self._name` (Single leading underscore). A convention warning other programmers: "This is meant for internal use, please don't touch it directly." (But Python won't stop them).
Private: `self.__name` (Double leading underscore). Python invokes "Name Mangling", heavily obfuscating the variable name so it cannot easily be accessed from outside the class.
To safely read/write private variables, we write public `getter` and `setter` methods.
Page 10
Wink Notes
B.Tech CSE — 3rd Semester
Python Programming
— Unit - 4 —
10. Inheritance
Inheritance allows a new class (Child/Derived Class) to inherit all the attributes and methods of an existing class (Parent/Base Class). It promotes massive code reuse.
⇒10.1 Syntax
The parent class is passed as an argument to the child class definition.
```python class Animal: # Parent def eat(self): print("Eating...")
class Cat(Animal): # Child inherits from Animal def meow(self): print("Meow")
c = Cat() c.meow() c.eat() # Inherited method works perfectly! ```
Page 11
Wink Notes
B.Tech CSE — 3rd Semester
Python Programming
— Unit - 4 —
11. super() and Overriding
⇒11.1 Method Overriding
If a child class defines a method with the exact same name as a method in the parent class, the child's method overrides (replaces) the parent's method for objects of the child class.
⇒11.2 The `super()` Function
Often, a child class wants to add to the parent's `__init__`, rather than completely replacing it. `super()` acts as a proxy to call the parent class's methods.
```python class Employee: def __init__(self, name, salary): self.name = name self.salary = salary
class Manager(Employee): def __init__(self, name, salary, department): # Call parent's init to handle name and salary super().__init__(name, salary) self.department = department ```
Page 12
Wink Notes
B.Tech CSE — 3rd Semester
Python Programming
— Unit - 4 —
12. Multiple Inheritance
Unlike Java, Python fully supports Multiple Inheritance (a child class inheriting from two or more parent classes simultaneously).
```python class Flyer: def fly(self): pass
class Swimmer: def swim(self): pass
class Duck(Flyer, Swimmer): pass ```
⇒12.1 The Diamond Problem & MRO
If both parent classes define a method with the same name (e.g., `move()`), which one does the child inherit? Python solves this using the Method Resolution Order (MRO) algorithm (specifically C3 Linearization). It searches for the method from Left to Right through the parents. In the Duck example, it would check `Flyer` before `Swimmer`.
Page 13
Wink Notes
B.Tech CSE — 3rd Semester
Python Programming
— Unit - 4 —
13. Polymorphism and Magic Methods
Polymorphism means "many forms". In OOP, it refers to the ability of different object classes to be treated as instances of the same class through a common interface.
Example: You can call `.draw()` on a Circle object, a Square object, and a Triangle object. Each object executes its own specific drawing code, but the interface (`draw()`) is the same.
⇒13.1 Magic Methods (Operator Overloading)
How does Python know that `+` adds numbers, but concatenates strings? Through polymorphism via Magic Methods.
You can define how operators work for your Custom Classes by defining specific "Dunder" methods:
`__str__(self)`: Defines what prints when you `print(obj)`.
`__add__(self, other)`: Defines what happens when you do `obj1 + obj2`.
`__eq__(self, other)`: Defines what happens when you do `obj1 == obj2`.
Page 14
Wink Notes
B.Tech CSE — 3rd Semester
Python Programming
— Unit - 4 —
14. Summary Checklist
Unit 4 bridges Python scripts into professional software architecture.
⇒14.1 University Exam Checklist
Write a Python script to open a file, append a line of text to it, and close it using the `with` statement.
Explain the concept of OOP. What is the difference between a Class and an Object?
What is the purpose of the `__init__` method? Why is `self` required as the first parameter?
How does Python implement data encapsulation and private variables? (Name Mangling).
Define Inheritance. Provide a code example showing a parent class, a child class, and the use of `super()`.
What is Method Overriding?
Explain Multiple Inheritance and how Method Resolution Order (MRO) resolves naming conflicts.