A class is a blueprint. From one blueprint you can create many objects, and each one has its own data. One Monster class, a hundred different monsters.
YOUR FIRST CLASS
class Monster:
def __init__(self, name, hp):
self.name = name
self.hp = hp
slime = Monster("Slime", 10)
bat = Monster("Bat", 6)
print(slime.name, slime.hp)
print(bat.name, bat.hp)Slime 10
Bat 6
__init__runs automatically when you create an object. It sets up the starting values.selfmeans "this particular object".self.hpis an attribute: data that belongs to the object.
METHODS: THINGS AN OBJECT CAN DO
A method is a function that lives inside a class.
class Monster:
def __init__(self, name, hp):
self.name = name
self.hp = hp
def take_hit(self, damage):
self.hp = max(0, self.hp - damage)
if self.hp == 0:
print(self.name, "is defeated!")
slime = Monster("Slime", 10)
slime.take_hit(4)
print(slime.hp)
slime.take_hit(9)6
Slime is defeated!
EACH OBJECT HAS ITS OWN DATA
class Counter:
def __init__(self):
self.count = 0
def click(self):
self.count += 1
a = Counter()
b = Counter()
a.click()
a.click()
b.click()
print(a.count, b.count)2 1
WHAT DOES THIS PRINT?
class Hero:
def __init__(self, name):
self.name = name
self.coins = 0
def collect(self, n):
self.coins += n
h = Hero("Ana")
h.collect(5)
h.collect(3)
print(h.coins)Each call adds to the same object's
coins: 0 + 5 + 3 = 8.INHERITANCE: A CLASS BASED ON ANOTHER
class Monster:
def __init__(self, name):
self.name = name
def roar(self):
return self.name + " growls"
class Dragon(Monster):
def roar(self):
return self.name + " breathes fire!"
print(Monster("Wolf").roar())
print(Dragon("Smog").roar())Wolf growls
Smog breathes fire!
Dragon gets everything from Monster and replaces only roar().
COMMON BEGINNER MISTAKES
Forgetting
self as the first parameter of a method, or writing hp instead of self.hp.Misspelling
__init__. It has two underscores on each side. With one, it never runs.Calling the class without creating an object. First
slime = Monster("Slime", 10), then slime.take_hit(4).PRACTICE IT, DON'T JUST READ IT
In Class Castle you design Hero and Monster classes and make them fight, one small method at a time.
PLAY CLASS CASTLE ▸FAQ
What is self in Python?
self is the object the method is working on. It lets each object keep and change its own data, like self.hp.
What does __init__ do?
It runs automatically when you create an object and sets its starting values.
What is the difference between a class and an object?
The class is the blueprint (Monster). An object is one thing made from it (slime = Monster("Slime", 10)).