Code

Blueprints for Things

So far you've stored related data in dicts and tuples. That works, but nothing stops a typo like potion["powr"], and the data has no behavior of its own. A class fixes both: it's a blueprint for making objects.

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

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

What just happened?

  • class Lantern: defines the blueprint. Class names use CapWords.
  • Calling Lantern("Mossreach", 5) builds a new instance (an object).
  • Python automatically runs __init__ on the new object. Its first parameter, self, is that new object.
  • self.island = island creates an attribute: a value stored on the object. Read it later with a dot: beacon.island.

Every call makes a separate object with its own attributes, just like every [] makes a separate list.

Pip tip: __init__ has two underscores on each side ("dunder init"). One underscore, or a typo like __int__, and Python silently skips it!

Assignment

  1. Complete Potion.__init__(self, name, power).
  2. Store name and power as attributes with the same names.
  3. Every new potion also starts with a uses attribute equal to 3.