Classes and Objects
Object-oriented programming in Python: classes, instances, methods, attributes, and __init__.
What you'll learn
- Define classes with the class keyword
- Initialize objects with __init__ and self
- Create instance methods and attributes
- Use class variables and static methods
- Understand __str__ and __repr__ for string representation
Concept
Defining a Class
A class is a blueprint for creating objects. Use the class keyword, and follow PEP 8 by using PascalCase for class names:
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
return f"{self.name} says Woof!"
The __init__ method is the constructor — it runs when you create a new instance. The self parameter refers to the current instance (like this in other languages) and must be the first parameter of every instance method.
Creating Instances
my_dog = Dog("Rex", 3)
print(my_dog.name) # Rex
print(my_dog.bark()) # Rex says Woof!
your_dog = Dog("Buddy", 5)
print(your_dog.age) # 5
Each instance has its own copy of the instance attributes. my_dog and your_dog are independent objects with their own name and age.
Instance vs Class Variables
class Dog:
species = "Canis familiaris" # class variable — shared by all instances
def __init__(self, name):
self.name = name # instance variable — unique per instance
rex = Dog("Rex")
buddy = Dog("Buddy")
print(rex.species) # Canis familiaris (from class)
print(buddy.species) # Canis familiaris (same class variable)
Class variables are defined on the class itself and shared by all instances. Instance variables are defined in __init__ (with self.) and are unique to each instance. Modifying a class variable through an instance actually creates a new instance variable that shadows it.
Methods
class Calculator:
@staticmethod
def add(a, b):
return a + b
@classmethod
def description(cls):
return f"{cls.__name__} — a simple calculator"
print(Calculator.add(2, 3)) # 5 — called on the class
print(Calculator.description()) # Calculator — a simple calculator
- Instance methods — take
self, operate on an instance @staticmethod— noselforcls, behaves like a regular function inside the class@classmethod— takescls(the class), often used for alternative constructors
__str__ and __repr__
These "dunder" (double underscore) methods control how your object appears as a string:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
# User-friendly string — used by print() and str()
return f"({self.x}, {self.y})"
def __repr__(self):
# Developer-friendly string — used by repr() and in the REPL
return f"Point({self.x!r}, {self.y!r})"
p = Point(3, 4)
print(p) # (3, 4) — uses __str__
print(repr(p)) # Point(3, 4) — uses __repr__
__str__ is for end users; __repr__ is for developers and should ideally be a valid Python expression that could recreate the object. If only __repr__ is defined, it is used as a fallback for __str__.
Properties
Use @property to turn a method into a computed attribute:
class Circle:
def __init__(self, radius):
self.radius = radius
@property
def area(self):
import math
return math.pi * self.radius ** 2
c = Circle(5)
print(c.area) # 78.54... — accessed like an attribute, not a method
Properties let you add computed attributes without changing the interface — callers access c.area as if it were a simple attribute, but it is computed on the fly.
Example
# A simple class
class Dog:
species = "Canis familiaris" # class variable
def __init__(self, name, age):
self.name = name # instance variables
self.age = age
def bark(self):
return f"{self.name} says Woof!"
def __str__(self):
return f"Dog(name={self.name}, age={self.age})"
# Creating instances
rex = Dog("Rex", 3)
buddy = Dog("Buddy", 5)
print(rex.bark()) # Rex says Woof!
print(rex.species) # Canis familiaris
print(rex) # Dog(name=Rex, age=3)
# Static and class methods
class Calculator:
@staticmethod
def add(a, b):
return a + b
@classmethod
def description(cls):
return f"{cls.__name__} — a simple calculator"
print(Calculator.add(2, 3))
print(Calculator.description())
# Properties for computed attributes
class Circle:
def __init__(self, radius):
self.radius = radius
@property
def area(self):
import math
return math.pi * self.radius ** 2
@property
def circumference(self):
import math
return 2 * math.pi * self.radius
c = Circle(5)
print(f"Area: {c.area:.2f}") # 78.54
print(f"Circumference: {c.circumference:.2f}") # 31.42
Shows a Dog class with class/instance variables, __str__, instance creation, static and class methods, and a Circle class with @property for computed area and circumference.
Try it
- JSON Formatter
Objects are often serialized to JSON — practice formatting structured data.
- Case Converter
Class and method naming conventions (PascalCase, snake_case).
Common mistakes
The mistake
Forgetting self as the first parameter of instance methods
The fix
Every instance method must have 'self' as its first parameter. Python passes the instance automatically — you do not include it in the call. Omitting it causes TypeError about missing arguments.
The mistake
Defining class variables that are mutable (like lists) and sharing them across instances
The fix
A mutable class variable is shared by all instances — modifying it in one affects all. Define mutable per-instance data in __init__ with self. Use class variables only for immutable shared constants.
Related Resources
Related Cheatsheets
- Python Cheatsheet
Class definition, methods, properties, and dunder methods.
Practice Classes and Objects
8 exercises
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Build real projects
Apply what you learned by building guided projects with starter code and solutions.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.