← Python from Scratch Lesson 60 of 78 · 10 XP

Classes and objects

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

Until now, data (variables) and actions (functions) lived separately. A class brings them together: it's a blueprint from which objects are made.

class Cat:
    def speak(self):
        return "Meow"

murka = Cat()        # an object (instance) of the Cat class
barsik = Cat()       # another object from the same blueprint
murka.speak()        # 'Meow'

A function inside a class is called a method. It is called with a dot: object.method().

You've been using objects for a long time: the string "text" is an object of the str class, and .upper() is its method. A list is an object of the list class with the .append() method.

Why classes? When "things" appear in a program — a player, a product, a bank account — it's convenient to keep a thing's data and the actions on it in one place.

Class names are customarily written with a capital letter and without underscores: BankAccount, GameCharacter.

Task. Create a class Cat with a method speak() that returns the string Meow, and a class Dog with a method speak() that returns Woof.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.