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.