Classes and Objects
Prerequisites: Functions, Dictionaries
Object-oriented programming groups related data and behavior together into a class — a blueprint — and each individual object made from it is called an instance.
Syntax
class ClassName:
def __init__(self, ...):
...
Example
class User:
def __init__(self, name, role):
self.name = name
self.role = role
def greet(self):
return f"Hi, I'm {self.name}"
ada = User("Ada", "admin")
print(ada.greet())
print(ada.name)
Expected output
Hi, I'm Ada
Ada
__init__ is the constructor — it runs automatically when you create a
new instance (User("Ada", "admin")). Every method takes self as its
first parameter, which refers to the specific instance the method is
being called on.
Common mistakes
- Forgetting
selfas a method's first parameter, or forgetting to writeself.name(accessing justnameinstead) inside a method.
Practice
Write a Rectangle class with width and height, and a method area()
that returns width * height.
Show solution
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
r = Rectangle(4, 5)
print(r.area())