Learn Python: Basics of Classes, Methods, and Encapsulation for Beginners

Introduction
Coming from a basic JavaScript background, I often found myself confused when writing methods in Python. For some reason, I kept equating them with variables in my mind. I'm not entirely sure why, but that’s how it was.
What are Classes
Classes are the fundamental part of object-oriented programming in Python. They create the "shape" of an object. Think of them as molds. They can define what an object "looks" like, but they can be filled with many different properties, or "attributes," and behaviors, or "methods."
For example, if we have a car. The car would be the class. This class defines what attributes the car has, such as color, make, and model. It also defines its behaviors, like accelerate, stop, or start.
Here is a simple example:
class Person:
def __init__(self, age, eye_color, hair_color):
self.age = age
self.eye_color = eye_color
self.hair_color = hair_color
# Creating an instance of the Person class
my_person = Person(30, "blue", "brown")
print(f"I am a person who is {my_person.age} years old.")
Here we see that we have defined a class of "Person," and within this class, we have given it the attributes of age, eye color, and hair color. A syntax note here: we use __init__
, which is a special method called a constructor. This allows our object's attributes to be initialized. Also, notice that we have to target self
to refer to the instance of the class itself.
What are Methods
Methods in Python are functions that belong to a class. We use these to define the behaviors of the class and the results that can come from them.
What is Encapsulation
Encapsulation is abstracting complexity. For instance, functions are a form of encapsulation. It's like your computer: there are many parts inside it; however, you don't need to know how each part works in order for you to be able to use it.
In Python, we can achieve encapsulation by using naming conventions to indicate what "parts" are intended for internal use, allowing us to avoid accidental use outside their intended scope.
Public: These are accessible from anywhere and are the default in Python.
Protected: These are accessible only within the class or sub-classes. We write them like this:
_protected_attribute
.Private: These are only used within the class itself. These are written like this:
__private_attribute
. The double underscore makes it more difficult to access directly from outside the class.
Putting the Pieces Together
The best way to understand these concepts is to see them in action. Here is the code for the Car
class I built, which demonstrates how classes, methods, and encapsulation work together.
class Car:
"""A class to represent a car and demonstrate encapsulation."""
def __init__(self, make, model):
"""Initializes the Car with a make, model, and a private speed attribute."""
self.make = make
self.model = model
# The speed attribute is made private with a double underscore.
self.__speed = 0
def accelerate(self):
"""Increases the car's speed by 1."""
self.__speed += 1
print(f"The {self.make} {self.model} is now accelerating. Current speed: {self.__speed} mph")
def brake(self):
"""Decreases the car's speed by 1, but prevents it from going below 0."""
if self.__speed > 0:
self.__speed -= 1
print(f"The {self.make} {self.model} is now braking. Current speed: {self.__speed} mph")
else:
print(f"The {self.make} {self.model} has already stopped.")
def get_speed(self):
"""Returns the current speed of the car. This is a public accessor method."""
return self.__speed
# Example of how to use the Car class
my_car = Car("Ford", "Mustang")
my_car.accelerate()
my_car.accelerate()
my_car.brake()
print(f"The car's final speed is: {my_car.get_speed()} mph.")
In the example above, we have created the Car
class and initialized it with two public attributes (make
and model
) and one private attribute (__speed
). In order to manipulate the behavior of the class, we have added methods that allow us to accelerate
and brake
, as well as a public method to get_speed
.
Conclusion
It's easy to get tangled up in new concepts, especially when you're transitioning from one language to another. But once you start to see how these pieces fit together, object-oriented programming in Python becomes a powerful way to organize your thoughts and your code.
Classes allow you to model real-world things in your programs, methods give them life, and encapsulation ensures they behave exactly as you intend. Embracing these concepts is the next step on your journey to becoming a more skilled and confident Python developer.
Now that you've got the foundation, try building a class of your own. Maybe a Dog
class with methods like bark()
or wag_tail()
, or a Bank Account
with methods for deposit()
and withdraw()
. The best way to master these ideas is to put them into practice!
Subscribe to my newsletter
Read articles from David Gagnon directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
