Code

Methods & self

A method is a function defined inside a class. It describes something an object can do. Its first parameter is always self: the object the method was called on.

class Lantern:
    def __init__(self, island, fuel):
        self.island = island
        self.fuel = fuel

    def describe(self):
        return f"{self.island}: {self.fuel} fuel"

beacon = Lantern("Mossreach", 5)
print(beacon.describe())  # Mossreach: 5 fuel

When you write beacon.describe(), Python quietly turns it into Lantern.describe(beacon). That's why you never pass self yourself: the object before the dot becomes self.

Methods can read and change attributes, so the object remembers what happened to it:

    def refuel(self, amount):
        self.fuel += amount

Assignment

Finish the three methods of Lantern:

  1. burn(hours) lowers fuel by hours, but never below 0. It returns the fuel that is left.
  2. refuel(amount) adds amount to fuel (returns nothing).
  3. is_lit() returns True when fuel is greater than 0, otherwise False.