🚧 Under construction — VoTechWorks is being built. A free tech program — complimentary, as our commitment to get America working.
voTechWorksGrade 13 · a vocational technology learning center, by urbanicity
newSchoolWorks.com › VoTechWorks › Technology & Design › Web & Software Development › PHP and Python Web Programming › Lesson 8
TEC-WEB46-03 · Lesson 8 · 13 clock hours · lab

Python Object-Oriented Programming and File I/O

Objective. Students define Python classes with attributes, __init__, instance methods, and basic inheritance, and read and write text and CSV files using Python's built-in open() function and the csv module, aligning with PCEP supplemental objectives and foundational OOP concepts

⚠ Pending professional review

This lesson, its worked examples and its practice questions has not yet been verified by an industry-certified professional or by a certification or approval body. It is a study draft and may contain errors. Do not use it as instructions for work on a job site or on live equipment. Always follow your instructor, your supervising professional, and current official references and regulations.

VoTechWorks program approval and accreditation are still in progress. Credentials are issued only by the certifying bodies named in each program, after their own exams.

Python Classes and Object-Oriented Programming

Object-oriented programming (OOP) organizes code around objects — bundles of data and behavior. In Python, you define a blueprint for objects using the `class` keyword. Each object created from that blueprint is called an instance.

Defining a Class

A class typically has:

```python

class Product:

def __init__(self, name, price, quantity):

self.name = name

self.price = price

self.quantity = quantity

def total_value(self):

return self.price * self.quantity

```

To create an instance and call a method:

```python

item = Product("Widget", 9.99, 50)

print(item.total_value()) # 499.5

```

Inheritance

Inheritance lets one class (the subclass) reuse and extend the behavior of another (the parent class). The subclass names the parent in parentheses and can override any method to change its behavior.

```python

class DiscountedProduct(Product):

def __init__(self, name, price, quantity, discount):

super().__init__(name, price, quantity)

self.discount = discount # fraction, e.g. 0.10 for 10%

def total_value(self):

discounted_price = self.price * (1 - self.discount)

return discounted_price * self.quantity

```

`super().__init__(...)` calls the parent's `__init__` so you do not repeat code. `DiscountedProduct.total_value()` overrides the parent version to apply the discount before multiplying.

Reading and Writing Files with `open()`

Python's built-in `open()` function provides access to files on disk. Always use it with a `with` statement (a context manager) so the file closes automatically, even if an error occurs — this prevents data loss and resource leaks.

```python

with open("report.txt", "w") as f:

f.write("Inventory Summary\n")

f.write("Total value: $499.50\n")

with open("report.txt", "r") as f:

contents = f.read()

print(contents)

```

Common mode strings: `"r"` (read), `"w"` (write, overwrites), `"a"` (append).

Working with CSV Files

A CSV (Comma-Separated Values) file stores tabular data as plain text. Python's `csv` module makes reading and writing safe and reliable — it handles edge cases such as commas inside quoted fields.

```python

import csv

with open("products.csv", "r", newline="") as f:

reader = csv.DictReader(f)

for row in reader:

print(row["name"], row["price"])

```

`csv.DictReader` maps each row to a dictionary using the header row as keys. Always pass `newline=""` when opening a CSV file for the `csv` module — this is noted in the Python docs and prevents blank-line issues on some operating systems.

Handling Errors with try/except

File operations can fail. A missing file raises `FileNotFoundError`. Malformed data (a non-numeric price field, for example) raises `ValueError`. Wrap risky code in `try/except` blocks:

```python

try:

with open("products.csv", "r", newline="") as f:

reader = csv.DictReader(f)

for row in reader:

try:

price = float(row["price"])

qty = int(row["quantity"])

except (ValueError, KeyError):

print(f"Skipping malformed row: {row}")

continue

except FileNotFoundError:

print("products.csv not found. Check the file path.")

```

Handling errors gracefully — rather than letting the program crash — is a professional expectation and protects the integrity of any output file your script creates.

Putting It Together

Your lab script will: (1) open the instructor-provided CSV, (2) attempt to create a `Product` object for each valid row, (3) accumulate total inventory value, and (4) write a summary report to a `.txt` file. Use the `with` statement for every file you open.

Peer Code Review: What Makes a Good Comment

During peer review, read your partner's class definition and test script. Write two comments in your lab log:

1. One about readability — Is `self` used consistently? Are variable names clear? Is there a docstring?

2. One about correctness — Does `total_value()` return the right number? Does the subclass call `super().__init__`?

Be specific: cite the line number and explain what you observed. Vague comments such as "looks good" do not meet the pass requirement.

Safety and Good Practice

Always validate data before writing it to a file — writing corrupt output is harder to fix than catching the error early. Keep credentials (passwords, API keys) out of source files. Never commit real customer data to a shared repository. Back up test datasets before running a script that opens files in write mode, because `"w"` mode overwrites without warning.

Key terms8

classA Python keyword used to define a blueprint for objects, grouping related attributes and methods together.
__init__A special method automatically called when a new instance is created; it initializes the object's attributes.
instanceA single object created from a class blueprint; each instance has its own copy of the class's attributes.
inheritanceAn OOP mechanism where a subclass automatically acquires the attributes and methods of a parent class and can override or extend them.
super()A built-in Python function that returns a proxy to the parent class, commonly used in __init__ to call the parent's constructor without repeating code.
context managerA Python construct (used with the `with` statement) that ensures setup and cleanup code runs reliably — for example, guaranteeing a file is closed after use.
csv.DictReaderA class in Python's csv module that reads each row of a CSV file as an ordered dictionary, using the header row as keys.
FileNotFoundErrorA built-in Python exception raised when open() cannot locate the specified file; it should be caught with a try/except block in production scripts.

Worked examples4

1. A Product has name='Bolt', price=2.50, quantity=200. What does total_value() return?
  1. Identify the formula: total_value = price × quantity
  2. Substitute values: 2.50 × 200
  3. Multiply: 2.50 × 200 = 500.00
Answer: total_value() returns 500.00
2. A DiscountedProduct has price=50.00, quantity=10, discount=0.20 (20%). What does its overridden total_value() return?
  1. Calculate the discounted price: 50.00 × (1 − 0.20) = 50.00 × 0.80 = 40.00
  2. Multiply discounted price by quantity: 40.00 × 10 = 400.00
Answer: total_value() returns 400.00
3. A CSV file contains three valid product rows with total values of $120.00, $85.50, and $400.00, plus one malformed row that is skipped. What value should the summary report show as total inventory value?
  1. List valid totals: 120.00, 85.50, 400.00
  2. Add them: 120.00 + 85.50 = 205.50
  3. 205.50 + 400.00 = 605.50
  4. The malformed row is skipped and contributes $0.00
Answer: The summary report should show a total inventory value of $605.50
4. A DiscountedProduct has price=120.00, quantity=5, discount=0.15 (15%). What is the total_value()?
  1. Calculate discounted price: 120.00 × (1 − 0.15) = 120.00 × 0.85 = 102.00
  2. Multiply by quantity: 102.00 × 5 = 510.00
Answer: total_value() returns 510.00

The math in this lesson1

Learners code total value as price x quantity and a 20% discount: $50.00 x 0.80 = $40.00.
7.RP.3
Brush up in the math halls at newSchoolWorks.com:
In class: Students design and implement a Product class with attributes (name, price, quantity), a method to calculate total value, and a subclass DiscountedProduct that overrides the price calculation; they write a test script that creates instances and prints results · File I/O lab: students write a script that reads a CSV file of product records, creates Product objects, computes total inventory value, and writes a summary report to a new text file — they handle FileNotFoundError and malformed rows with try/except · Peer code review: students exchange their Product class code with a partner, run it against a shared test dataset, and write two specific, constructive comments in the lab log about readability and correctness
Materials: Python 3 docs (csv module, built-in open()), instructor-provided CSV dataset, VS Code, student lab log template
Check: Product and DiscountedProduct classes produce correct output for all test cases; file I/O script handles FileNotFoundError gracefully and writes a correct summary report; peer review comments are substantive — pass requires all three components complete and correct

Practice check8

Answer each question, then check it. Nothing is recorded; this is your own practice.

PCEP — Object-Oriented Programming basics
1. Which special method is automatically called when a new Python object is instantiated from a class?
PCEP — Object-Oriented Programming basics
2. In the definition `class DiscountedProduct(Product):`, what does placing `Product` in parentheses accomplish?
PCEP — Object-Oriented Programming basics
3. What is the purpose of `super().__init__(...)` inside a subclass constructor?
PCEP — Input/Output operations
4. Which of the following correctly opens a file for reading using a context manager in Python?
PCEP — Input/Output operations
5. When opening a CSV file for use with Python's csv module, which keyword argument should be passed to open()?
PCEP — Exception handling
6. A script tries to open 'inventory.csv' but the file does not exist. Which exception is raised?
PCEP — Object-Oriented Programming basics
7. A DiscountedProduct has price=80.00, quantity=4, and discount=0.25. What is the return value of total_value()?
PCEP — Professional practices / code quality
8. During peer code review, which comment best meets the 'substantive and specific' standard required by this lab?
Record this lesson on my transcript. Sign in with your key and enrollment email to record lessons (enroll free if you have no key). This page stays open to read and practise.