Legends ofPythos
Claim your name
Objects and Classes

Your first class

Lesson 2 of 13

Watch the lesson1:03 · with Torsten
A class is a blueprint for creating objects. Think of it as a cookie cutter: the shape defines what every cookie looks like, but each individual cookie can be different.

Defining a class

class Dog:
    pass

class Cat:
    pass
Two simple classes. The name uses CapWords (each word capitalized, no underscores).
By convention, class names use CapWords: every significant word starts with a capital letter and there are no separators. Dog is good; dog, dOG, or my_dog_class are not.

Creating an instance

class Dog:
    pass

dino = Dog()
rufus = Dog()
Dog() creates a new object. dino and rufus are two separate instances of the same class.
Calling the name like a function — Dog() — produces an instance. Each call makes a brand-new, independent object. The variable on the left is just a label pointing to that instance.

Instance attributes with self

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

dino = Dog('Dino')
rufus = Dog('Rufus')
print(dino.name)
print(rufus.name)
__init__ runs when you create an instance. self is the specific object being built.
self refers to this particular instance. When you write self.name = name, you are saying: "store this value on me, not on some other dog." Because every call gets its own self, each instance keeps its data separate.

Accessing attributes with a dot

class Book:
    def __init__(self, title):
        self.title = title

code_book = Book('Python Basics')
print(code_book.title)
code_book.title reads the attribute. Dot notation is how you reach into an object.

Your turn

0 of 3 solved

Exercise 1

+30 XP
Define a class called Player whose constructor takes one argument, name, and stores it as an instance attribute. Then create two instances: hero with the name 'Aria' and rival with the name 'Kai'. Finally, print both names using dot access.
Write your Python here.

Run your code to check it against the tests.

Exercise 2

+30 XP
Define a class called Point whose constructor takes two arguments, x and y, and stores them as instance attributes. Create an instance at coordinates (10, -5) named corner. Then print the sum of its x and y values.
Write your Python here.

Run your code to check it against the tests.

Exercise 3

+30 XP
Define a class called Inventory whose constructor takes one argument, items, which is a list. Store it as an instance attribute. Create two instances: backpack with ['sword', 'shield'] and pouch with ['coin']. Add the string 'key' to both inventories using their dot-accessed lists, then print the total number of items across both.
Write your Python here.

Run your code to check it against the tests.