Classes & objects, explained simply
A class is a blueprint. An object is a thing built from that blueprint. One Creature class can make a dragon, a fox and an owl, each with its own name and energy.
The special __init__ method runs when a new object is made. It stores the object’s details using self, which means "this particular object".
Methods are functions that belong to a class. Calling fox.rest() runs the method for that fox only, changing its energy but not anyone else’s.
Example: A creature blueprint
class Creature:
def __init__(self, name):
self.name = name
self.energy = 5
def rest(self):
self.energy = self.energy + 2
fox = Creature("Fox")
fox.rest()
print(fox.name, fox.energy)Output
Fox 7Try this
- Make a second creature and show that resting one does not change the other.
- Add a speak() method that prints a sound using the creature’s name.
- Give __init__ a second parameter so each creature can start with different energy.
