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. |
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.
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)
850
The class keeps balance rules near the balance data. deposit() and withdraw() protect the account better than editing balance from many places.
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())
Python Guide: INR 499
OOP Course: INR 999
currency is shared by the class, while name and price are stored separately on each 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. |
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)
Maya
Ravi
maya@example.com
Both objects use the same User class, but each object stores its own name and email values.
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())
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.
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())
open
done
The same task object remembers its done value. mark_done() changes the object, and status_label() reads the updated state.
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())
5
205
The cart object remembers items between method calls. item_count() and total() calculate from the data stored on that one cart.
0 of 2 checked
Try this next
0 of 3 completed
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.
Explore 500+ free tutorials across 20+ languages and frameworks.