
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:
burn(hours)lowersfuelbyhours, but never below0. It returns the fuel that is left.refuel(amount)addsamounttofuel(returns nothing).is_lit()returnsTruewhenfuelis greater than0, otherwiseFalse.
Finish the three methods of Lantern:
burn(hours)lowersfuelbyhours, but never below0. It returns the fuel that is left.refuel(amount)addsamounttofuel(returns nothing).is_lit()returnsTruewhenfuelis greater than0, otherwiseFalse.
main.py Python sleeping
Press Run to try your code, then Check to test it.