Creating Classes in Python (OOP)
An introduction to Object-Oriented Programming (OOP) in Python. Learn to create classes, define attributes, use the __init__() constructor, write methods, and organize classes into modules.
import { Callout } from '@/components/callout';
Creating Classes in Python (OOP)
Python is a powerful Object-Oriented Programming (OOP) language. At its core, this means that almost everything in Python is an object, complete with its own properties (attributes) and behaviors (methods). The blueprint for creating these objects is a class.
A class is a user-defined template from which objects are created. It bundles data and functionality together, forming the foundation of clean, modular, and reusable code.
The Basic class
Syntax
To create a class, you use the class
keyword followed by the class name and a colon. The body of the class is indented.
class ClassName:
# Statement 1
# Statement 2
# ...
# Statement N
<Example title="A Simple Car
Class">
Here's a basic class with two properties, model
and color
. We then create an instance of the class (an object) and access its properties using dot notation.
# Define the class
class Car:
model = "Volvo"
color = "Blue"
# Create an object (instance) of the Car class
my_car = Car()
# Access the object's properties
print(my_car.model) # Output: Volvo
print(my_car.color) # Output: Blue
</Example>
You can also define a class with empty properties and assign them values after the object has been created.
class Car:
model = ""
color = ""
# Create the first car instance
car1 = Car()
car1.model = "Ford"
car1.color = "Green"
print(f"Car 1 is a {car1.color} {car1.model}") # Output: Car 1 is a Green Ford
# Create a second car instance
car2 = Car()
car2.model = "Tesla"
car2.color = "Red"
print(f"Car 2 is a {car2.color} {car2.model}") # Output: Car 2 is a Red Tesla
The __init__()
Constructor
The previous approach is cumbersome. A much better way to initialize an object's properties is by using the special __init__()
method. This method is called a constructor, and it runs automatically every time a new object is created from the class.
The __init__()
method is where you define the initial state of the object. Its first parameter is always self
, which represents the instance of the class itself.
<Example title="Using __init__
to Create Objects">
By using __init__
, we can pass initial values as arguments when creating the object.
class Car:
def __init__(self, model, color):
# 'self' refers to the specific instance being created
# We are assigning the passed-in arguments to the instance's properties
self.model = model
self.color = color
# Now we can create instances with their properties in one line
car1 = Car("Ford", "Green")
car2 = Car("Volvo", "Blue")
print(car1.model) # Output: Ford
print(car2.color) # Output: Blue
</Example>
Object Methods
Functions that are defined inside a class are called methods. They define the behaviors of an object. Like __init__()
, their first parameter must always be self
, which gives them access to the object's properties and other methods.
<Example title="Adding a displayCar
Method">
Let's extend our Car
class with a method that prints the car's details.
class Car:
def __init__(self, model, color):
self.model = model
self.color = color
def displayCar(self):
print(f"Model: {self.model}")
print(f"Color: {self.color}")
# Create an instance
car1 = Car("Tesla", "Red")
# Call the instance's method
car1.displayCar()
# Output:
# Model: Tesla
# Color: Red
# We can still modify properties directly
car1.color = "Black"
car1.displayCar()
# Output:
# Model: Tesla
# Color: Black
</Example>
Organizing Classes in Separate Files
For better code organization, it's a best practice to define a class in its own file (a module) and then import it wherever it's needed.
<Example title="Importing a Class from a Module">
1. Create the class module (Car.py
):
Save the following code in a file named Car.py
.
# Filename: Car.py
class Car:
def __init__(self, model, color):
self.model = model
self.color = color
def displayCar(self):
print(f"Model: {self.model}")
print(f"Color: {self.color}")
2. Create the main script (testCar.py
):
In a separate file, you can import the Car
class from your Car.py
module.
# Filename: testCar.py
# From the 'Car' module, import the 'Car' class
from Car import Car
# Now you can use the class as if it were defined in this file
car1 = Car("Tesla", "Red")
car1.displayCar()
car2 = Car("Ford", "Green")
print(f"The second car is a {car2.model}.")
</Example>
<Exercise title="Temperature Converter Class"> Create a Python class for converting temperatures. The class should be able to convert a temperature from Celsius to Fahrenheit and vice versa.
The conversion formulas are:
- Celsius to Fahrenheit: $T_f = (T_c \times 9/5) + 32$
- Fahrenheit to Celsius: $T_c = (T_f - 32) \times (5/9)$
Your class should have methods to perform these conversions. For example, you might create an instance like temp = TemperatureConverter(celsius=25)
and then call a method like temp.to_fahrenheit()
.
</Exercise>