</>
Skip to content
Python lessons (24/45)

Python — Classes and Objects

Objects bundle data + behavior

A class is a blueprint; objects are things built from it:

class Dog:
    def __init__(self, name, age):     # runs on creation
        self.name = name               # attributes live on the object
        self.age = age

    def speak(self):                   # method = function in a class
        return f"{self.name} says woof!"

rex = Dog("Rex", 3)                    # instantiate
print(rex.speak())                     # Rex says woof!
print(rex.age)                         # 3

__init__ and self — the two newcomers

  • __init__ is the constructor: called automatically by Dog(...)
  • self is the current object — Python passes it explicitly as the FIRST parameter of every method
rex.speak()      # self = rex, silently

Forgetting self in the definition but calling with no args is the classic first-week error:

TypeError: speak() takes 0 positional arguments but 1 was given

Instance vs class attributes

class Dog:
    species = "Canis familiaris"       # CLASS attribute — shared by all

    def __init__(self, name):
        self.name = name               # INSTANCE attribute — per dog

a, b = Dog("Rex"), Dog("Bella")
a.species          # "Canis familiaris"
Dog.species        # same — one copy
a.name is b.name   # different — each has its own

Rule: shared constants → class level; per-object data → self. in __init__.

Methods that read and write state

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

    def deposit(self, amount):
        if amount <= 0:
            raise ValueError("must be positive")
        self.balance += amount
        return self.balance

    def withdraw(self, amount):
        if amount > self.balance:
            raise ValueError("insufficient funds")
        self.balance -= amount
        return self.balance

acct = BankAccount("Ada")
acct.deposit(100)
acct.withdraw(30)      # 70

Private-ish attributes: underscore convention

class Account:
    def __init__(self):
        self._internal = "hands off (convention)"
        self.__secret = "name-mangled"   # becomes _Account__secret

Python trusts you — _single means "please don't touch"; double underscore triggers name mangling.

Built-in niceties

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

    def __str__(self):                 # print() uses this
        return f"({self.x}, {self.y})"

p = Point(3, 4)
print(p)         # (3, 4)

When to use classes

Reach for one when data + the functions that operate on it travel together (accounts, players, API clients). Plain functions + dicts are fine for scripts — don't force OOP.

Gotchas: mutable default arguments (def __init__(self, items=[]) shares ONE list across instances!) · forgetting self · calling methods without parentheses.

Mini Practice

  1. Book class: title/author/pages + summary() method.
  2. Counter class with increment()/reset(); prove instances stay separate.
  3. Rectangle with area() and perimeter().
  4. Trigger the mutable-default bug; fix with None.
  5. Add str to any earlier class.

Next: inheritance →

Related Topics

Frequently Asked Questions about Classes and Objects

What is Classes and Objects in Python?

Classes and Objects is a fundamental concept in Python. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Classes and Objects?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Classes and Objects.

Why is Classes and Objects important in Python?

Classes and Objects is essential for Python development. Understanding this concept will help you write better code and solve real-world problems more effectively.