
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 useCapWords.- 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 = islandcreates 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
- Complete
Potion.__init__(self, name, power). - Store
nameandpoweras attributes with the same names. - Every new potion also starts with a
usesattribute equal to3.
- Complete
Potion.__init__(self, name, power). - Store
nameandpoweras attributes with the same names. - Every new potion also starts with a
usesattribute equal to3.
main.py Python sleeping
Press Run to try your code, then Check to test it.