What Are Python Classes and How Do You Create Them?
Python is an object-oriented programming (OOP) language, which means it is centered around the idea of “objects” that can contain data (such as attributes) and code (such as methods). Because Python is an OOP language, it allows for the creation of classes.
What are classes? I’m glad you asked. A class is a blueprint that is used to help organize and structure code for reusability and modularity. A good way to think of a class is that it is similar to a blueprint for a house. That blueprint can be used to create one house, several houses, a neighborhood of houses, or even an entire city of houses.
Because you have the blueprint, you already know how the house will be constructed, so it makes the process of building far more efficient. Of course, not all of those houses will be identical; they might be painted a different color, have additions or be decorated based on the owner’s taste. A great example of this is in the film “Poltergeist,” which features an entire neighborhood of houses that look as if they were built from the same blueprint.
Classes are also partially responsible for defining relationships and interactions between Python objects. Once a class has been created, you can then create a specific object that includes the attributes and behaviors that are defined by that class.
As you gain more experience with Python, you’ll come to understand just how crucial classes are when building complex applications.
But how do you create and use a class? That’s what we’re going to focus on here. Although classes might seem complicated, understanding their basic usage is fairly straightforward.
Let’s find out.
The Structure of a Class
The structure of a class is fairly simple; however, there are some key concepts to understand. One concept is the idea of self, which you’ve seen in many classes. The self parameter is the first parameter in a class declaration and is used to access variables belonging to that class. Although you don’t have to use the word “self,” you must always use the same word for the first parameter of any function in the class.
Here are three other concepts you should understand:
- Attributes are variables that hold class data.
- Methods are functions that provide behavior and act on the class data.
- The __init__ special method initializes an object with the attributes in the class. It’s often used in classes.
The basic structure of a class looks like this:
class ClassName: # Body of class
Fairly basic, but the structure of a class is straightforward. However, the creation of a class isn’t quite as simple. Let’s create a class called NoClass that has two attributes: name and age. We’ll also define a method that will initialize the class and define name and age, as well as a method called read_name that will return the details from within our object.
The class looks like this:
class NoClass:
def __init__(self, name, age):
self.name = name
self.age = age
def read_name(self):
return f"Name: {self.name}, Age: {self.age}"
Awesome. Now that we’ve created the class, how do we use it? First, we’ll define an object using our class and inject data into it:
object1 = NoClass("Jack Wallen", 55)
At this point, object1 now includes two pieces of data: “Jack Wallen” and 55, which can be accessed via the name and age details from the object.
Finally, we’ll access both the attributes and methods within our class with two print statements:
print(object1.name) print(object1.read_name())
The entire code block looks like this:
class NoClass:
def __init__(self, name, age):
self.name = name
self.age = age
def read_name(self):
return f"Name: {self.name}, Age: {self.age}"
object1 = NoClass("Jack Wallen", 55)
print(object1.name)
print(object1.read_name())
The output of the above would be:
Jack Wallen Name: Jack Wallen, Age: 55
Now let’s create a class that’s a bit more complicated. We’re going to create a class called Vehicle with three attributes: make, model and year. Then, we’ll define two methods called start_vehicle and stop_vehicle. Next, we create an instance of the car class by injecting data into a variable called my_vehicle from the Vehicle class. Finally, we’ll print out the information and call the two classes.
First, let’s define the class, like so:
class Vehicle: def __init__(self, make, model, year): self.make = make self.model = model self.year = year
Next, we’ll create our start_vehicle method:
def start_vehicle(self):
print(f"Your {self.year} {self.make} {self.model} has started.")
Now we’ll create our stop_vehicle method:
def stop_vehicle(self):
print(f"Your {self.year} {self.make} {self.model} has stopped.")
Next, let’s create an instance of the Vehicle class:
my_vehicle = Vehicle("Mini", "Cooper", 2021)
Finally, we’ll access both the attributes and methods of the instance with the print command and the my_vehicle instance:
print(f"My car is a {my_vehicle.year} {my_vehicle.make} {my_vehicle.model}.")
my_vehicle.start_vehicle()
my_vehicle.stop_vehicle()
The entire block of code looks like this:
class Vehicle:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
def start_vehicle(self):
print(f"Your {self.year} {self.make} {self.model} has started.")
def stop_vehicle(self):
print(f"Your {self.year} {self.make} {self.model} has stopped.")
my_vehicle = Vehicle("Mini", "Cooper", 2021)
print(f"My car is a {my_vehicle.year} {my_vehicle.make} {my_vehicle.model}.")
my_vehicle.start_vehicle()
my_vehicle.stop_vehicle()
If we run the above code, the output would be:
My car is a 2021 Mini Cooper. Your 2021 Mini Cooper has started. Your 2021 Mini Cooper has stopped.
The cool thing about what we just created is that we can reuse the class later on in the same program. For instance, we can define a new vehicle instance like so:
vehicle_1 = Vehicle("Audi", "A5", 2022)
And that’s the gist of Python classes. Remember: Classes can be used many times, so create them such that you’ll be inclined to repurpose them, which makes for more efficient programming.