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.
CT Links: Abstraction (hiding complexity with defaults), Decomposition (analyzing parameter variations).
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]!".
CT Links: Decomposition (defining actions separately), Abstraction (using `self` to access internal state).
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`.
CT Links: Modeling (representing multiple distinct items of the same type), Abstraction (each instance manages its own state).
Provided Class Definition:
class Counter:
def __init__(self, start=0):
self.count = start
def increment(self):
self.count += 1
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()`).
CT Links: Decomposition (distinguishing definition vs. execution), Pattern Recognition (identifying `instance.method()` syntax).
Advanced OOP Mini Missions!
Apply your refined OOP skills! Complete these tasks involving defaults, methods modifying state, and returning info.
CT Links: Modeling (more complex object behavior), Decomposition (methods with specific purposes), Abstraction.
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.