</>
Topic 10 of 10
Theory

Classes

A class is a blueprint for objects. __init__ runs when an object is created, self is the object itself:

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

    def speak(self):            # method
        return f"{self.name}: woof"

rex = Dog("Rex")
print(rex.speak())   # Rex: woof

The __len__ method lets you call len(obj), and any method can raise an exception when an action is impossible.

Cat

Easy+10 XP

Create a Cat class. It gets a name when created, and speak() returns <name>: meow.

Cat("Kitty").speak() → "Kitty: meow"
main.pyLoading Python…
Output
Press "Check" to run the tests