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
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.
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.
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 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.
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).
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.
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.
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.
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.
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.
Answer each question, then check it. Nothing is recorded; this is your own practice.
A free tech program — complimentary, as our commitment to get America working. Help us build VoTechWorks. Tell us what works, what doesn’t, and what you want to learn.