Python lesson 29

Classes and Objects. Your Own Kind of Thing

Build a blueprint once, then stamp out as many as you like.

A Blueprint and Its Copies

class defines the blueprint. __init__ runs whenever a new one is made, and self is that particular one. This enemy, not enemies in general. Functions inside a class are called methods, and they always take self first.

class Enemy:
def __init__(self, name, health):
self.name = name # store it on THIS enemy
self.health = health

def hit(self, damage):
self.health = self.health - damage

goblin = Enemy("Goblin", 30) # __init__ runs here
goblin.hit(10) # self is goblin

class Enemy:
    def __init__(self, name, health):
        self.name = name
        self.health = health

    def hit(self, damage):
        self.health = self.health - damage
        print(self.name, "now has", self.health, "health")

goblin = Enemy("Goblin", 30)
goblin.hit(10)

Two Copies, Two Lives

class Pet:
    def __init__(self, name):
        self.name = name

a = Pet("Rex")
b = Pet("Milo")
print(a.name)

Write the Blueprint

A Whole Battle

Two objects from one class, fighting. Run it.

class Fighter:
    def __init__(self, name, health, power):
        self.name = name
        self.health = health
        self.power = power

    def attack(self, other):
        other.health = other.health - self.power
        print(self.name, "hits", other.name, "for", self.power)

    def is_alive(self):
        return self.health > 0

hero = Fighter("Nova", 40, 12)
goblin = Fighter("Goblin", 30, 8)

while hero.is_alive() and goblin.is_alive():
    hero.attack(goblin)
    if goblin.is_alive():
        goblin.attack(hero)

winner = hero.name if hero.is_alive() else goblin.name
print("Winner:", winner)

Build Your Own Class

A Dog with a name and a trick. Change the name, change the trick, add a second dog.

class Dog:
    def __init__(self, name, trick):
        self.name = name
        self.trick = trick

    def show_off(self):
        print(self.name, "can", self.trick + "!")

rex = Dog("Rex", "roll over")
milo = Dog("Milo", "play dead")
rex.show_off()
milo.show_off()

A Counter That Remembers

An object can hold state between calls. Watch the count climb.

class Counter:
    def __init__(self):
        self.count = 0

    def click(self):
        self.count = self.count + 1
        return self.count

c = Counter()
c.click()
c.click()
print("Clicked", c.click(), "times")

What you can do on CodeIt

Run the example, change one part, and use the result to check your understanding before moving to the next lesson.