Skip to main content
  • Python is available now. All other compilers are coming soon.

    Python
  • Popular Tutorials

    • Getting Started With Python
    • Python if Statement
    • while Loop in Python
    • Python Lists
    • Dictionaries in Python
    All Python Tutorials

    Reference Materials

    Built-in FunctionsList MethodsDictionary MethodsString Methods
    View all

Online Compilers

  • Python Compiler
  • Python Playground
  • Python Projects
  • Exercises

Tutorials

  • Learn Python
  • Python for Beginners
  • Variables and Types
  • Python Strings
  • Python Lists
  • Python If Else
  • Python For Loops
  • Python Functions
  • Python Classes

Examples

  • Python Examples
  • Hello World
  • Add Two Numbers
  • Even or Odd
  • Factorial
  • Fibonacci
  • Prime Check
  • Palindrome Check

Company

  • About
  • Contact
  • Privacy Policy
  • Terms of Use
  • Disclaimer

© 2026 ILoveCompiler. All rights reserved.

  1. Home
  2. Python Tutorial
  3. Python Classes and Objects: A Practical Introduction

Object-oriented Python · Tutorial 23

Python Classes and Objects: A Practical Introduction

Define classes, create objects, use __init__ and methods, and model state without overengineering.

Open the compilerPractice exercises
intermediate10 min readUpdated November 19, 20264 learning goals
On this page
  1. init
  2. Attributes and methods
  3. Class attributes
  4. Readable representation
  5. Objects in collections
  6. Composition versus inheritance
  7. Practice

What you will learn

  • Define a class with attributes and methods
  • Use __init__ to initialise objects
  • Distinguish instance attributes from class attributes
  • Add a readable __repr__ method
Before this lesson: Python Functions: Define, Call, and Return Values, Python Error Handling with try, except, else, and finally

A class bundles data and behaviour. An object is an instance of a class.

Python
class Student:
    def __init__(self, name, score):
        self.name = name
        self.score = score

    def describe(self):
        return f"{self.name}: {self.score}"


student = Student("Ada", 95)
print(student.describe())
Expected output

Ada: 95

init#

__init__ runs when you create an object. It initialises the instance attributes.

Python
class Counter:
    def __init__(self, start=0):
        self.value = start

    def increment(self):
        self.value += 1

    def reset(self):
        self.value = 0


counter = Counter()
counter.increment()
counter.increment()
print(counter.value)  # 2

self refers to the object being operated on. It is the first parameter of instance methods and is passed automatically when you call the method.

Attributes and methods#

Attributes hold state; methods define behaviour:

Python
class Rectangle:
    def __init__(self, width, height):
        if width < 0 or height < 0:
            raise ValueError("Dimensions must be non-negative")
        self.width = width
        self.height = height

    def area(self):
        return self.width * self.height

    def perimeter(self):
        return 2 * (self.width + self.height)


box = Rectangle(3, 4)
print(box.area())        # 12
print(box.perimeter())   # 14

Validation in __init__ prevents objects from starting in an invalid state.

Class attributes#

An attribute defined on the class is shared unless an instance overrides it:

Python
class Circle:
    pi = 3.14159

    def __init__(self, radius):
        self.radius = radius

    def area(self):
        return Circle.pi * self.radius ** 2


print(Circle.pi)
print(Circle(2).area())

Mutable class attributes are shared across instances and are a common source of bugs. Put per-object data in __init__.

Readable representation#

__repr__ controls the developer-facing representation. It is useful in the console and in debugging output:

Python
class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __repr__(self):
        return f"Point(x={self.x}, y={self.y})"


print(Point(2, 5))
Expected output

Point(x=2, y=5)

print() uses __str__ when defined and falls back to __repr__ otherwise. For small data classes, a clear __repr__ is worth the two lines.

Objects in collections#

Python
class Task:
    def __init__(self, title, done=False):
        self.title = title
        self.done = done


tasks = [
    Task("Write outline"),
    Task("Draft tutorial", done=True),
]

for task in tasks:
    status = "done" if task.done else "pending"
    print(f"[{status}] {task.title}")

A list of objects is often clearer than a list of loosely related dictionaries once the data has behaviour or validation rules.

Composition versus inheritance#

Start with composition: an object uses other objects.

Python
class Engine:
    def start(self):
        return "Engine started"


class Car:
    def __init__(self):
        self.engine = Engine()

    def start(self):
        return self.engine.start()


print(Car().start())

Inheritance is appropriate when a subtype genuinely shares the parent's interface and behaviour. Do not introduce a hierarchy just to reuse one helper function; a plain function or composition is usually simpler.

Keep classes small

A class should have one main responsibility. If a class mixes file parsing, business rules, and console formatting, split it. Smaller classes are easier to test and reuse.

Practice#

Create a BankAccount class with an owner, balance, deposit(amount), and withdraw(amount). Reject negative amounts with ValueError and withdrawals above the balance with a custom exception. Create two accounts, perform several operations, and print each account using __repr__.

Previous tutorialPython Error Handling with try, except, else, and finally

Related tutorials

beginner

Python Dictionaries: Keys, Values, and Practical Patterns

Store and retrieve key-value data with dictionaries, iterate over items, and use get, update, and comprehensions.

9 min read
beginner

Python Tuples: Immutable Sequences and Unpacking

Use tuples for fixed groups of values, unpack them cleanly, and know when a tuple is a better choice than a list.

7 min read

On this page

  1. init
  2. Attributes and methods
  3. Class attributes
  4. Readable representation
  5. Objects in collections
  6. Composition versus inheritance
  7. Practice

Run the examples

Every Python block has a Run in compiler button that opens the code in a new tab.