Python Classes and Objects
Python classes and objects are the core of object-oriented programming (OOP) in Python. A class is a blueprint that describes what data an object holds and what it can do. An object is a single instance built from that blueprint. In fact, everything in Python, from numbers to lists, is an object.
Create a Class
Use the class keyword. The special method __init__ runs automatically when a new object is created and sets up its attributes.
class Product:
def __init__(self, name, price):
self.name = name
self.price = price
tea = Product("Green Tea", 6.0)
oil = Product("Olive Oil", 18.75)
print(tea.name, tea.price)
print(oil.name, oil.price)Green Tea 6.0 Olive Oil 18.75
What Is self?
self is the first parameter of every method and refers to the object the method was called on. When you write tea.name, Python looks up the name stored on that specific object. You never pass self yourself; Python fills it in.
Methods
Methods are functions defined inside a class. They can read and change the object's attributes through self.
class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
if amount > self.balance:
print("Insufficient funds")
return
self.balance -= amount
acc = BankAccount("Sara")
acc.deposit(200)
acc.withdraw(500)
acc.withdraw(50)
print(acc.owner, acc.balance)Insufficient funds Sara 150
Class Attributes and __str__
An attribute defined directly in the class body is shared by all objects. The __str__ method controls what print() shows for an object.
class Circle:
pi = 3.14159 # class attribute, shared
def __init__(self, radius):
self.radius = radius
def area(self):
return round(Circle.pi * self.radius ** 2, 2)
def __str__(self):
return f"Circle(radius={self.radius})"
c = Circle(3)
print(c)
print(c.area())Circle(radius=3) 28.27
Properties
The @property decorator lets a method be read like an attribute. It is useful for values calculated from other attributes.
class Rectangle:
def __init__(self, w, h):
self.w = w
self.h = h
@property
def area(self):
return self.w * self.h
r = Rectangle(4, 5)
print(r.area)
r.w = 10
print(r.area)20 50
Data Classes
For classes that mainly hold data, the dataclasses module writes __init__, __repr__ and comparison methods for you.
from dataclasses import dataclass
@dataclass
class Customer:
name: str
city: str
orders: int = 0
c = Customer("Liam Wilson", "New York")
print(c)
print(c == Customer("Liam Wilson", "New York"))Customer(name='Liam Wilson', city='New York', orders=0) True
Frequently asked questions
What is the difference between a class and an object in Python?
A class is the definition or blueprint. An object is a concrete instance created from it, with its own attribute values. One class can produce many objects.
What does self mean in Python?
self refers to the current object inside a method. It lets each method access and change that object's own attributes.
Is __init__ a constructor in Python?
It is usually called the constructor. Technically __new__ creates the object and __init__ initialises it, but in everyday code __init__ is where you set up attributes.
When should I use a dataclass?
Use a dataclass when a class mostly stores fields, such as records or settings. It removes boilerplate code and gives you a readable repr and equality checks.