LearnPy Hub
IntermediateIntermediateLesson 18 of 32

Classes & Objects

Watch the ideaA class is a blueprint for objects
class Dog:
    def __init__(self, name):
        self.name = name

    def speak(self):
        return self.name + " says woof"
class Dog (blueprint)
objects

A class describes what every object of that kind has and can do.

1Level 1 · BasicsBasics

As programs grow, it helps to bundle related data and the functions that work on it together. That's what classes do. This style is called object-oriented programming (OOP), and much of Python, including strings, lists and pandas DataFrames, is built from classes.

Class vs object

A class is a blueprint, like the design of a car. An object (or instance) is one actual thing built from it: your red car, my blue car. Every object made from the same class has the same kinds of data and abilities, but its own values.

Defining a class

class Student:
    def __init__(self, name, marks):
        self.name = name        # attributes: data stored in the object
        self.marks = marks

    def average(self):          # a method: a function that belongs to the class
        return sum(self.marks) / len(self.marks)
  • __init__ is the constructor. It runs automatically when you create an object and sets up its attributes.
  • self means "this particular object". Every method takes it as the first parameter, but you don't pass it yourself; Python does.
  • self.name = name stores a value inside the object so other methods can use it later.

Creating and using objects

s1 = Student("Mim", [88, 92, 79])
s2 = Student("Rafi", [70, 65, 81])
print(s1.name)          # attribute
print(s2.average())     # method call

Changing an object's state

Methods can update attributes. A BankAccount might have deposit() and withdraw() methods that change self.balance, and refuse a withdrawal that's too big. Keeping those rules inside the class means the rest of the program can't put the account into a broken state.

Class attributes

A variable written directly in the class body (not on self) is shared by all objects, for example a counter of how many students exist, or a constant like interest_rate.

Why bother?

Classes make code easier to understand: account.deposit(500) says exactly what's happening. They also let you create many independent objects from one blueprint, and they're the foundation for inheritance, which comes in the next lesson.

Key points: a class is a blueprint and an object is one instance of it; __init__ sets up attributes; methods take self first; use obj.attribute and obj.method().

See it in actionAn object keeps its own data

Watch acc's attributes inside the object, and how each deposit() call changes self.balance.

Step-by-step

Try it yourselfExample 1: Your first class

Two Student objects share the same blueprint but hold different data.

example_1.py
Output appears here
Fill in the blanks

Build a Dog

Fill the blanks so the class stores the name and the program prints Rex says woof.

blanks.py
class Dog:
    def (self, name):
        .name = name

    def speak(self):
        print(self.name, "says woof")

Dog("Rex").speak()

Example 2: A bank account

Methods change the object's state and protect its rules.

example_2.py
Output appears here
Fix the bug

Forgot self

This bank account should print 150 after a deposit of 50, but it crashes. Fix the method.

buggy.py
Your turn

Rectangle class

Write a class Rectangle with width and height, and a method area() that returns width × height. Print Rectangle(5, 4).area(), which is 20.

my_code.py

Example 3: Class attributes are shared

count belongs to the class itself, so every object adds to the same counter.

example_3.py
Output appears here
Fill in the blanks

Shared counter

Fill the blanks so every new Student adds 1 to a counter shared by the class, and the program prints 2.

blanks.py
class Student:
    count = 0
    def __init__(self, name):
        self.name = name
        .count  1

Student("Ana")
Student("Bo")
print(Student.count)

Example 4: A list of objects

Objects work well in lists, just like numbers and strings do.

example_4.py
Output appears here
Your turn

Oldest pet

Make a class Pet with name and age. Create three pets — Milo 3, Luna 7, Coco 5 — in a list and print the name of the oldest: Luna.

my_code.py

2Level 2 · IntermediateProperties, class methods and validation

__str__ and __repr__

Define __str__ to control what print(obj) shows, and __repr__ for a developer-friendly version (used in lists and the debugger).

@property

A property looks like an attribute but runs code. Use it for computed values (rect.area) or to validate on assignment with a setter, so a balance can never become negative.

@classmethod and @staticmethod

A class method receives the class (cls) and is often an alternative constructor: Student.from_csv("Mina,8,4.9"). A static method is a plain helper that lives in the class.

"Private" by convention

A leading underscore (self._balance) means "internal; use the methods instead".

See it in actionObjects keep their own state

Watch two Counter objects, each with its own count inside.

Step-by-step

Example 5: A bank account that validates itself

The setter refuses a negative balance; from_string builds an account from text.

example_5.py
Output appears here

3Level 3 · AdvancedComposition, __slots__ and design

Composition: "has a"

A Library has books; it isn't a book. Build objects out of other objects and let each one do its own job. Prefer this to deep inheritance.

Equality and hashing

By default two objects are equal only if they're the same object. Define __eq__ (and __hash__ if you want them in sets or as keys) to compare by value.

__slots__

__slots__ = ("x", "y") fixes which attributes an object can have. It saves memory when you create millions of objects and catches typos like p.z = 1.

Single responsibility

Each class should have one reason to change. If a class loads files, does maths and prints reports, split it.

Example 6: A library made of books

Library delegates to Book objects instead of inheriting from them.

example_6.py
Output appears here

Example 7: __slots__ saves memory and catches typos

The slotted point refuses a misspelled attribute.

example_7.py
Output appears here
Common mistakeForgetting self: writing def average(): causes TypeError: average() takes 0 positional arguments but 1 was given, and writing name = name instead of self.name = name means the value is never stored in the object.
Exercise · predict the output

What does this print?

class Counter:
    def __init__(self):
        self.n = 0
    def add(self):
        self.n += 1
c = Counter()
c.add()
c.add()
print(c.n)
Quick quiz · 5 questions
1. What is the relationship between a class and an object?
2. When does __init__ run?
3. What does self refer to inside a method?
4. How do you call the method average on the object s?
5. Where is a class attribute stored?
Ready to practice classes & objects?

50 graded problems are waiting in Topic Practice.

Practice this topic →
Python Classes & Objects · LearnPy Hub