๐Ÿงฌ Section 5: Add "Override Hooks" (Power Methods)

๐Ÿ“ Summary (What you will do)

In this section, you will add three small methods inside class Animal that return default "power" values. These methods are hooks that subclasses can override later to customize behavior without rewriting the whole action.


โœ… Checklist (You must complete these)

  • Open pet_manager.py
  • Find class Animal
  • Locate the shared action methods: feed(), play(), and clean()
  • Right after those methods, add the three hook methods shown below
  • Type the code by hand so you understand the pattern

โœ… No new constants/settings are added in this section, so you do not need to edit the top-of-file constants.


๐ŸŽ“ Core Concepts (New learning for this section)

1) Override hooks

An override hook is a small method meant to be replaced in a subclass. The base class provides a default version so the program works even if nothing is overridden.

Example idea:

  • Animal.play() calls self.play_power()
  • A Dog can override play_power() to return a larger number
  • The play() method stays the same, but dogs feel more playful

2) Default behavior in the base class

These hooks give every animal a reasonable default:

  • feed_power() -> 20
  • play_power() -> 18
  • clean_power() -> 22

If a subclass does nothing, it still behaves correctly.

3) Clean customization without copy-paste

Instead of rewriting play() in every subclass, we only override the hook. This keeps the code short, focused, and easier to maintain.


๐Ÿ’ป Code to Write (Type this by hand in pet_manager.py)

Directions:

  1. Open pet_manager.py
  2. Find class Animal
  3. Scroll to the shared action methods (feed, play, clean)
  4. Right after those methods, type the following code by hand:

Code image: s05-code


๐Ÿง  Code Review & Key Concepts (What important lines do)

Hook method: feed_power()

def feed_power(self) -> int:
    return 20

This returns the default amount of hunger reduction when feeding. Subclasses can override it to change the number.

Hook method: play_power()

def play_power(self) -> int:
    return 18

This returns the default happiness boost when playing. Dogs will later override it to be higher.

Hook method: clean_power()

def clean_power(self) -> int:
    return 22

This returns the default cleanliness increase when cleaning. Cats will later override it to be lower.


๐Ÿงช Test File: s05_test.py

โœ… Create this file

Create a new file in the same folder as pet_manager.py called:

s05_test.py

๐Ÿ’ป Code to write in s05_test.py

Code image: s05-test

๐Ÿง  What this test is doing (and how it works)

  • Animal is abstract, so we create TestAnimal and implement special_action()
  • We call feed_power(), play_power(), and clean_power() directly
  • The printed outputs should match the expected default values

โœ… Run the test:

python s05_test.py

If the values match, your override hooks are working correctly.