Tutorials Logic, IN info@tutorialslogic.com

Python Classes and Objects: OOP Basics

Read this page in two passes: First understand the class as the design. Then understand the object as the real value created from that design.

Python Class

A Python class defines a new type for your program. It describes the data an object should remember and the actions that should work with that data.

Use a class when a real concept in your program has a name, state, and behavior. Good class names are usually nouns such as User, Account, Product, Cart, Order, or Task.

The class body normally contains methods. The __init__ method receives the starting values, and self stores values on the object that Python is creating.

Class Part Purpose
class User: Starts a new class named User.
def __init__(self, name): Sets the first values every new object needs.
self.name = name Stores data on the object being created.
def display_name(self): Defines an action that each object can run.
currency = "INR" Stores a shared class attribute when all objects need the same value.
  • Prefer a function when one calculation or action is enough.
  • Prefer a class when several actions must protect or reuse the same data.
  • Write self as the first parameter of normal instance methods.
  • Store object-specific values with self.attribute inside __init__.
  • Keep changing lists, dictionaries, and counters on the object unless they are truly shared.

Define a User Class

Define a User Class
class User:
    def __init__(self, name, email):
        self.name = name
        self.email = email

    def display_name(self):
        return self.name.title()

User is the class. __init__ prepares the data each future user object needs, and display_name() is a method that will work with one user object at a time.

Protect Data with Methods

Protect Data with Methods
class BankAccount:
    def __init__(self, owner, opening_balance=0):
        if opening_balance < 0:
            raise ValueError("opening balance cannot be negative")
        self.owner = owner
        self.balance = opening_balance

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

    def withdraw(self, amount):
        if amount > self.balance:
            raise ValueError("not enough balance")
        self.balance -= amount


account = BankAccount("Anika", 1000)
account.deposit(250)
account.withdraw(400)
print(account.balance)
Output
850

The class keeps balance rules near the balance data. deposit() and withdraw() protect the account better than editing balance from many places.

Use a Class Attribute Only for Shared Data

Use a Class Attribute Only for Shared Data
class Product:
    currency = "INR"

    def __init__(self, name, price):
        self.name = name
        self.price = price

    def label(self):
        return f"{self.name}: {self.currency} {self.price}"


book = Product("Python Guide", 499)
course = Product("OOP Course", 999)

print(book.label())
print(course.label())
Output
Python Guide: INR 499
OOP Course: INR 999

currency is shared by the class, while name and price are stored separately on each object.

Python Object

A Python object is one real value created from a class. If User is the class, then User("Maya", "maya@example.com") creates one User object.

Each object has its own attributes. Two objects can be made from the same class and still remember different names, emails, balances, statuses, or cart items.

After an object exists, dot notation is how you use it: object.attribute reads stored data, and object.method() runs an action for that object.

Object Code Meaning
user = User("Maya", "maya@example.com") Creates one object from the User class.
user.email Reads the email stored on that object.
user.display_name() Runs a method for that object.
cart.add_item("Pen", 15) Changes the state of one cart object.
  • Create an object by calling the class like a function.
  • Use dot notation to read attributes and call methods.
  • Changing one object does not change another object made from the same class.
  • Call normal instance methods on an object, not directly on the class.
  • Use objects when the program needs to remember state between actions.

Create Two User Objects

Create Two User Objects
class User:
    def __init__(self, name, email):
        self.name = name
        self.email = email

    def display_name(self):
        return self.name.title()


user_one = User("maya", "maya@example.com")
user_two = User("ravi", "ravi@example.com")

print(user_one.display_name())
print(user_two.display_name())
print(user_one.email)
Output
Maya
Ravi
maya@example.com

Both objects use the same User class, but each object stores its own name and email values.

  • User is the class. user_one and user_two are separate objects.
  • Changing user_one.name would not change user_two.name.
  • display_name() uses self.name, so each object gets its own display result.

Read Data and Call Methods

Read Data and Call Methods
class User:
    def __init__(self, name, email):
        self.name = name
        self.email = email

    def display_name(self):
        return self.name.title()


user = User("maya", "maya@example.com")

print(user.email)
print(user.display_name())
Output
maya@example.com
Maya

user.email reads stored data. user.display_name() runs a method for the same object, and Python passes user as self automatically.

Change Object State Over Time

Change Object State Over Time
class TodoItem:
    def __init__(self, title):
        self.title = title
        self.done = False

    def mark_done(self):
        self.done = True

    def status_label(self):
        return "done" if self.done else "open"


task = TodoItem("Review Python objects")
print(task.status_label())
task.mark_done()
print(task.status_label())
Output
open
done

The same task object remembers its done value. mark_done() changes the object, and status_label() reads the updated state.

Build a Cart Object

Build a Cart Object
class ShoppingCart:
    def __init__(self, owner):
        self.owner = owner
        self._items = []

    def add_item(self, name, price, quantity=1):
        if quantity <= 0:
            raise ValueError("quantity must be positive")
        self._items.append((name, price, quantity))

    def total(self):
        return sum(price * quantity for _, price, quantity in self._items)

    def item_count(self):
        return sum(quantity for _, _, quantity in self._items)


cart = ShoppingCart("Maya")
cart.add_item("Notebook", 80, 2)
cart.add_item("Pen", 15, 3)

print(cart.item_count())
print(cart.total())
Output
5
205

The cart object remembers items between method calls. item_count() and total() calculate from the data stored on that one cart.

Class-object readiness check

Can You Explain Class and Object Separately?

6 checks
  • Define a class as the code that describes object data and behavior.
  • Create an object by calling the class with real values.
  • Use __init__ to store starting object attributes.
  • Use self to read or change the current object.
  • Choose class attributes only for values shared by every object.
  • Write methods that protect object state with clear validation.

Class Object Decisions

0 of 2 checked

Q1. What is a class in beginner-friendly terms?

Q2. Why does an instance method usually need self?

Class and Object Mixups

  • Creating a class for one calculation

    Use a function when there is no state to remember between actions.
  • Forgetting self

    Instance methods need self so they can read and change the current object.
  • Putting object data on the class by accident

    Use self.name and self.balance for data that belongs to each object.

Try this next

Model a Small Account

0 of 3 completed

  1. Create a Book class with title, author, and a short description method.
  2. Create a BankAccount class with deposit and withdraw methods that update balance.
  3. Decide whether calculator tax, user profile, and shopping cart should be functions or classes.

Questions About Class Object

Functions model actions. Classes model things that remember state and provide actions for that state. If one action is enough, use a function. If several actions work on the same data, a class may be clearer.

self is the object receiving the method call. It lets the method read and update that specific object instead of some global value.

Put the starting attributes every object needs, such as name, email, balance, width, or height. Do not put temporary calculation values there unless the object must remember them later.

Browse Free Tutorials

Explore 500+ free tutorials across 20+ languages and frameworks.