COSC 2306: Data Programming

Chapter 3: Interactive OOP Exercises

Instructions

This interactive lab reinforces the Object-Oriented Programming concepts from Chapter 3. Modify the code in the editor boxes below and click "Run Code" to see the result.

Note: Python acts strictly. Watch your indentation!

Exercise 1: The Blueprint

As stated in the slides, a class creates a new type, while objects are instances of that class.

Task: Define a class named Dog. Inside, use the pass keyword (a placeholder). Then, create an instance of the class named my_dog and print it.

Exercise 2: The Constructor (__init__)

The __init__ method is the constructor. It initializes instance attributes using self.

Task: Update the class to accept name and age. Create a dog named "Buddy" who is 5 years old.

Exercise 3: Behavior (Methods)

Methods are functions that belong to an object. Remember the slides: the first parameter must always be self!

Task: Create a method called bark() that prints "Woof! My name is [name]".

Exercise 4: The String Representation

By default, printing an object looks ugly (e.g., <__main__.Dog object at 0x...>). We use the __str__ magic method to make it human-readable.

Task: Implement __str__ to return a nice sentence describing the dog.

import sys from js import document, window from io import StringIO def run_exercise(ex_id): code_element_id = f"code-{ex_id}" output_element_id = f"output-{ex_id}" output_div = document.getElementById(output_element_id) # 1. Get code via the JS helper function try: # We call the JS function `window.get_code` we defined above user_code = window.get_code(code_element_id) except Exception as e: output_div.innerText = f"System Error accessing editor: {e}" return # 2. Clear previous output output_div.innerHTML = "" # 3. Redirect stdout old_stdout = sys.stdout redirected_output = StringIO() sys.stdout = redirected_output try: local_scope = {} # 4. Execute the code exec(user_code, globals(), local_scope) # 5. Get captured output result = redirected_output.getvalue() if not result and user_code.strip(): result = "[Code ran successfully, but printed nothing.]" elif not user_code.strip(): result = "[No code to run]" output_div.innerText = result output_div.classList.remove("text-red-400") output_div.classList.add("text-white") except Exception as e: output_div.innerText = f"Error: {e}" output_div.classList.remove("text-white") output_div.classList.add("text-red-400") finally: sys.stdout = old_stdout