Python Classes/Objects
Object-Oriented Python Object-Oriented Python

Python Classes and Objects

1Python Classes/Objects: overview

A class is a blueprint that describes what data a kind of thing holds and what it can do; an object is one concrete thing built from that blueprint, with its own copy of the data.

GoalBy the end you can define a class with init, create several objects from it, read and change their attributes, write methods that use self, and give objects a readable str and repr.

Before this lesson: Python Dictionaries, Python Functions

2Python Classes/Objects: diagram

Python Classes and Objectsnamesobjects (instances)owner="Asha" balance=150BankAccount objectowner="Ben" balance=15BankAccount objectacct1acct2One class, two objects: each object keeps its own attributes
The class BankAccount is the blueprint; acct1 and acct2 are two separate objects made from it. Changing one object's balance does not touch the other's.

3Python Classes/Objects: explained step by step

So far you have kept data in variables, lists and dictionaries, and written functions that work on that data. A class lets you keep the data and the functions that belong to it together, under one name.

Class vs object

Think of a class as a cookie cutter and objects as the cookies. The class BankAccount describes what every account has (an owner and a balance) and what it can do (take a deposit). Each account you create — acct1, acct2 — is a separate object, also called an instance, with its own values.

__init__ and self

When you call a class like a function, BankAccount("Asha", 120), Python creates a new, empty object and immediately runs its __init__ method to set it up. The first parameter, self, is that new object. Writing self.owner = owner stores a value on the object; a value stored like that is called an attribute.

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

rex = Dog("Rex", 3)
bella = Dog("Bella", 5)
print(rex.name, rex.age)
print(bella.name, bella.age)

You never pass self yourself — Python fills it in. That is why __init__ above has three parameters but Dog("Rex", 3) passes only two arguments.

Methods

A method is a function defined inside a class. Its first parameter is always self, so it can read and change the attributes of the object it was called on. You call it with a dot: acct1.deposit(50). Behind the scenes Python runs BankAccount.deposit(acct1, 50).

Each object has its own attributes

Changing acct1.balance leaves acct2.balance alone, because attributes set on self belong to one object. A variable written directly in the class body, outside any method, is a class attribute instead: it is shared by every object, which is handy for constants such as an interest rate.

Dunder methods: __str__ and __repr__

Methods whose names start and end with two underscores ("dunder" methods) let your objects work with Python's built-in features. By default, printing an object shows something unhelpful like <__main__.Book object at 0x7f...>. Define __str__ to choose what print() and str() show, and __repr__ for a precise, developer-friendly version — Python uses it when the object appears inside a list or in error messages.

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

    def __str__(self):
        return f"{self.title} ({self.pages} pages)"

    def __repr__(self):
        return f"Book({self.title!r}, {self.pages})"

novel = Book("Dune", 412)
print(novel)
print([novel])

Both methods must return a string — not print it.

Quick reference: Python Classes/Objects

4Python Classes/Objects: syntax

class ClassName:
    shared = "value"                 # class attribute (shared by all objects)

    def __init__(self, a, b):        # runs when an object is created
        self.a = a                   # instance attribute
        self.b = b

    def method(self, x):             # self = the object it was called on
        return self.a + x

    def __str__(self):               # what print(obj) shows
        return f"ClassName({self.a}, {self.b})"

obj = ClassName(1, 2)                # create an object (an instance)
obj.a                                # read an attribute
obj.method(10)                       # call a method -> 11

5Python Classes/Objects: run the example

Press Run (or Ctrl + Enter). The output (step 6) appears directly below the code. Change anything and run it again.

Interactive example
class BankAccount:
    def __init__(self, owner, balance=0):
        self.owner = owner
        self.balance = balance

    def deposit(self, amount):
        self.balance += amount

    def __str__(self):
        return f"{self.owner}: ${self.balance}"

acct1 = BankAccount("Asha", 120)
acct2 = BankAccount("Ben")
acct1.deposit(30)
acct2.deposit(15)

print(acct1)
print(acct2)
print("Ben's balance:", acct2.balance)
Expected outputAsha: $150
Ben: $15
Ben's balance: 15

7Python Classes/Objects: how the example works

Hover or tap a step to highlight its lines in the example above.

  1. Line 1class BankAccount: starts the blueprint. Defining a class does not create any accounts yet.
  2. Line 2-4__init__ runs every time a new account is created. It stores the owner and the starting balance as attributes on self; balance=0 is a default value.
  3. Line 6-7deposit is a method. self.balance += amount changes the balance of whichever object the method is called on.
  4. Line 9-10__str__ returns the text that print() should show for an account.
  5. Line 12-13Calling the class creates two separate objects. Python passes each new object to __init__ as self. Ben's account uses the default balance of 0.
  6. Line 14-15In acct1.deposit(30), self is acct1, so only Asha's balance changes (to 150). Ben's account gets 15.
  7. Line 17-18print() calls each object's __str__ method to get the text to display.
  8. Line 19You can read an attribute directly with a dot: acct2.balance is the number 15.

8Python Classes/Objects: common mistakes

Forgetting self in a method definition

✗ Wrong

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

    def increase():
        self.count += 1

clicks = Counter()
clicks.increase()
TypeError: Counter.increase() takes 0 positional arguments but 1 was given

✓ Right

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

    def increase(self):
        self.count += 1

clicks = Counter()
clicks.increase()
print(clicks.count)

Python always passes the object as the first argument of a method, so every method needs self as its first parameter.

Storing values without self.

✗ Wrong

class Player:
    def __init__(self, name):
        name = name
        score = 0

mia = Player("Mia")
print(mia.name)
AttributeError: 'Player' object has no attribute 'name'

✓ Right

class Player:
    def __init__(self, name):
        self.name = name
        self.score = 0

mia = Player("Mia")
print(mia.name)

name = name only creates a local variable that disappears when __init__ ends. Store values on the object with self.name = ....

Using a class attribute list for per-object data

✗ Wrong

class Team:
    members = []

    def add(self, name):
        self.members.append(name)

red = Team()
blue = Team()
red.add("Asha")
print(blue.members)
Prints ['Asha'] — Asha appears in the blue team too

✓ Right

class Team:
    def __init__(self):
        self.members = []

    def add(self, name):
        self.members.append(name)

red = Team()
blue = Team()
red.add("Asha")
print(blue.members)

A list in the class body is created once and shared by every object. Create the list in __init__ so each object gets its own.

9Python Classes/Objects: exercises

Write your answer, then press Check. The checks run in your browser.

1. Build a Rectangle class

Write code Easy

Write a class Rectangle whose __init__ takes width and height and stores them as attributes with those names. Add a method area() that returns width * height.

Your code
class Rectangle:
    # write __init__(self, width, height) that stores both values on self
    # write area(self) that returns width * height
    pass

room = Rectangle(4, 5)
print(room.area())

2. Predict the counters

Predict the output Medium

Two Counter objects are created and clicked. Type exactly what the program prints.

Read this code
class Counter:
    def __init__(self, start=0):
        self.value = start

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

a = Counter()
b = Counter(10)
a.click()
a.click()
print(b.click())
print(a.value, b.value)

2 more exercises → 4 more examples

Finished this lesson?
Progress is saved in this browser — create a free account to keep it across devices.

Questions learners ask

What is self in Python?

self is the object a method was called on. When you write acct.deposit(50), Python runs deposit with self set to acct, so self.balance means acct's balance. The name self is a convention, but every Python programmer uses it.

What is the difference between a class and an object?

A class is the definition — the blueprint that lists attributes and methods. An object (instance) is one thing created from that blueprint by calling the class, like BankAccount("Asha"). One class can create any number of independent objects.

Should I define __str__ or __repr__?

Define repr first: it is used in lists, the console and debugging, and print() falls back to it when there is no str. Add str when you also want a friendlier version for end users.

Further reading

10Next lesson

Up nextPython Class Attributes vs Instance AttributesA class attribute is a variable stored once on the class and shared by every object, while an instance attribute is sto…

Related:
Python Class Attributes vs Instance AttributesPython Encapsulation: Public, Protected and PrivatePython Dunder (Magic) Methods

← Python pathlib · All Object-Oriented Python lessons · Practise in the IDE