Module 29: Advanced OOP Practice

Refining classes, building methods, and handling multiple objects.

Refining `__init__`: Default Values

Sometimes, attributes should have a starting value if none is provided. Click the parts of this `__init__` method to see how default parameters work.

def __init__(self, name, species="Unknown"):
    self.name = name
    self.species = species  # Uses provided or default value

Identify all 6 parts!

Build a Method

Methods define what an object can *do*. Drag pieces to build a `greet` method for a `Person` class (assume `self.name` exists). It should take `other_name` and print a greeting like "Hi [other_name], I'm [self.name]!".

Drop pieces here for the greet method...

Multi-Instance Simulator

You can create many objects (instances) from the same class blueprint. Using the `Counter` class below, create *two* instances: `c1` (starting at 0) and `c2` (starting at 5). Then, increment `c1` once and print the `count` for both `c1` and `c2`.

Provided Class Definition:

class Counter:
    def __init__(self, start=0):
        self.count = start

    def increment(self):
        self.count += 1
Output will appear here...

Spot the Method Call

Creating an instance is one step, making it *do* something involves calling its methods. Click on the line(s) below where a method is actually being *called* on an instance (e.g., `object.method()`).

Advanced OOP Mini Missions!

Apply your refined OOP skills! Complete these tasks involving defaults, methods modifying state, and returning info.

Mission 1: `Lamp` Class with Default

Define a class `Lamp`. Its `__init__` should take `self` and `watts`. It should also take `is_on` with a *default value* of `False`. Assign both `watts` and `is_on` to instance attributes.

Mission 2: `toggle` Method

Add a method called `toggle` to the `Lamp` class (rewrite the whole class). This method takes only `self`. Inside `toggle`, change the value of the `self.is_on` attribute to its opposite (if it was `True`, make it `False`, and vice-versa).

Mission 3: `get_status` Method

Add another method `get_status` to the `Lamp` class (rewrite the whole class again). This method takes only `self`. It should *return* a string: `"Lamp is on"` if `self.is_on` is `True`, and `"Lamp is off"` if it's `False`.

Module 29 Advanced Practice Complete!

Fantastic! You've tackled default values, methods interacting with attributes, and multiple instances.
You're building a solid OOP foundation. Consider watching the video lesson or revisiting the theory for deeper understanding.