Introduction to Python Classes and Object-Oriented Programming [A Beginner's Guide]
To run Python from the command prompt or PowerShell on your PC, you need to download and install Python.
If you havenβt installed it yet, please refer to the article Setting Up Python and Development Environment to install Python.
Hello to everyone just stepping into the world of web development! This time, we're going to explain "Object-Oriented Programming (OOP)," an important concept used in many programming languages, and Python's core component, the "class," in a way that's easier to understand than anywhere else. There's no need to be intimidated by technical terms. By the time you finish this article, you'll surely be thinking, "Oh, I get it now!"
The main goal of this article is to let you experience the "joy of seeing code work." Let's put the difficult theory aside for now and start by playing with code you can copy and paste to get a real feel for the convenience of object-oriented programming!
What Is Object-Oriented Programming, Anyway?
When you hear "Object-Oriented," it might sound difficult, right? But it's actually a concept that's all around us in our daily lives.
A very common analogy is a "cookie cutter" and a "cookie."
- Class: This is the "cookie cutter." It serves as the blueprint, defining the shape and what ingredients (like chocolate chips or nuts) it will have.
- Object: This is the individual "cookie" made from the "cookie cutter." Even if made from the same cutter, some might have different toppings or be slightly more baked, giving each its own unique characteristics.
In the world of programming, once you create this "blueprint" (the class), you can efficiently create many concrete "things" (objects) from it. This is the fundamental idea of object-oriented programming. For a website, treating elements like "users," "blog posts," or "products" as individual objects allows you to keep even complex systems neatly organized.
The Basics of Python Classes: Let's Create a Blueprint
Alright, let's dive right in and create a "blueprint," or class, in Python. We'll use a Dog theme for this section.
1. The Simplest Class
First, let's define a class with nothing inside. Even this is a valid "blueprint."
# Define a class (blueprint) named Dog
class Dog:
pass # pass means "do nothing." It's used when a statement is syntactically required but you have no code to execute.
# Create a concrete dog object (instance) from the Dog class
my_dog = Dog()
# Let's print out what my_dog is
print(my_dog)
Execution Result:
<__main__.Dog object at 0x10e28a2d0>
Looking at the result, you can see that an object of the Dog class was created. (The `0x...` part will vary depending on your execution environment).
2. Giving Individuality with the `__init__` Method
Next, just like adding chocolate chips to a cookie, let's give our dog specific information (called properties or attributes) like a "name" and "breed." To do this, we use a special method (a function inside a class) called `__init__`. This is an initializer method that runs automatically the moment an object is created.
class Dog:
# The initializer method, automatically called when an object is created
def __init__(self, name, breed):
# Save data to the object using the self.variable_name format
self.name = name
self.breed = breed
print(f"{self.name} ({self.breed}) was born!")
# Create a "Shiba Inu" object named "Pochi"
dog1 = Dog("Pochi", "Shiba Inu")
# Create an "Akita" object named "Hachi"
dog2 = Dog("Hachi", "Akita")
# Let's display the name and breed of each
print(f"First dog's name: {dog1.name}")
print(f"First dog's breed: {dog1.breed}")
print(f"Second dog's name: {dog2.name}")
print(f"Second dog's breed: {dog2.breed}")
The first argument of `__init__`, `self`, is a special keyword that refers to the instance being created. Think of it as a convention. By writing `self.name = name`, you're tying data to the object, as in "this object's name is..."
Execution Result:
Pochi (Shiba Inu) was born!
Hachi (Akita) was born!
First dog's name: Pochi
First dog's breed: Shiba Inu
Second dog's name: Hachi
Second dog's breed: Akita
Just by calling the class like `Dog("Pochi", "Shiba Inu")`, the `__init__` method is executed, creating objects with their respective information. You can access the information an object holds by using a `.` (dot), like `dog1.name`.
3. Defining Behavior with Methods
Objects can have not only data (attributes) but also "behaviors" (methods). For a dog, let's add the behavior of "barking."
class Dog:
def __init__(self, name, breed):
self.name = name
self.breed = breed
# Add a behavior (method) for the dog to bark
def bark(self):
return f"{self.name}: Woof woof!"
# Create an object
my_dog = Dog("Koro", "Mixed Breed")
# Call the bark method
greeting = my_dog.bark()
print(greeting)
You just define a function inside the class using `def`. Again, don't forget to include `self` as the first argument. Through `self`, you can access the object's own name (`self.name`).
Execution Result:
Koro: Woof woof!
Advanced Topic: Reusing Blueprints with Class "Inheritance"
This is where object-oriented programming gets really powerful. Using a mechanism called "inheritance," you can easily create a new class by adding or changing functionality based on an existing class (blueprint).
For example, let's create a new "GuideDog" class based on our previous `Dog` class. A guide dog is a type of dog, so it has a "name" and "breed" and the basic ability to "bark." In addition, it has the special job (method) of "assisting people."
# The base parent class (superclass)
class Dog:
def __init__(self, name, breed):
self.name = name
self.breed = breed
print(f"A dog named {self.name} was born. The breed is {self.breed}.")
def bark(self):
return f"{self.name}: Woof!"
# Create a new child class (subclass) that inherits from the Dog class
class GuideDog(Dog): # Write the parent class's name in the parentheses
def assist(self):
return f"{self.name} is safely guiding a person."
# Create a GuideDog object
g_dog = GuideDog("Elle", "Labrador Retriever")
# Methods from the parent class (Dog) can also be used
print(g_dog.bark())
# The unique method added in the child class (GuideDog)
print(g_dog.assist())
By simply writing the base class name in the parentheses after the new class name, like `class GuideDog(Dog):`, the inheritance is complete. Just like that, `GuideDog` inherits all of a `Dog`'s attributes (`name`, `breed`) and methods (`bark`). This greatly increases code reusability and is very efficient.
Execution Result:
A dog named Elle was born. The breed is Labrador Retriever.
Elle: Woof!
Elle is safely guiding a person.
Practical Example: A Class to Manage Blog Posts
Now, let's look at an example that's closer to a real-world web production scenario. We'll create a `BlogPost` class to manage articles on a blog site. An article has a "title," "content," and "author," and we'll give it a function to "display the post."
import textwrap
class BlogPost:
def __init__(self, title, content, author):
self.title = title
self.content = content
self.author = author
# A method to display the article's information neatly
def display(self):
print("--------------------")
print(f"Title: {self.title}")
print(f"Author: {self.author}")
print("--- Content ---")
# Wrap and display long text
print(textwrap.fill(self.content, width=40))
print("--------------------")
# Create multiple post objects
post1 = BlogPost(
"Introduction to Python Classes",
"Object-oriented programming is a way of thinking where you assemble programs like components. A class is a blueprint, and an object is the actual instance.",
"Taro Yamada"
)
post2 = BlogPost(
"The Basics of Web Design",
"Good design considers not only visual beauty but also user-friendliness as its top priority. Whitespace and color schemes are crucial.",
"Hanako Sato"
)
# Display the articles
post1.display()
post2.display()
By treating each article as an object like this, the data (like the title) and the behavior (the display function) are bundled together, making management much easier.
Execution Result:
--------------------
Title: Introduction to Python Classes
Author: Taro Yamada
--- Content ---
Object-oriented programming is a way of
thinking where you assemble programs like
components. A class is a blueprint, and
an object is the actual instance.
--------------------
--------------------
Title: The Basics of Web Design
Author: Hanako Sato
--- Content ---
Good design considers not only visual
beauty but also user-friendliness as its
top priority. Whitespace and color
schemes are crucial.
--------------------
[Try It Yourself!] A Complete Python Code Sample
The wait is over! Here, we present the complete code for a "User Management Program" that brings together everything we've covered. You can save this code as a `.py` file and run it from your computer's terminal (or command prompt). Go ahead and experience the "joy of seeing it work!"
How to Run
- Copy the entire code block below.
- Paste it into a text editor (like VSCode) and save it with the name `user_manager.py`.
- Open your terminal and navigate to the directory where you saved the file.
- Type `python user_manager.py` and press Enter.
If you don't have Python installed on your PC, please download it from python.org.
# user_manager.py
class User:
"""
A class to represent user information for a website
"""
def __init__(self, user_id, name, email):
self.user_id = user_id
self.name = name
self.email = email
self.is_active = True # Active user by default
def get_profile(self):
"""
Formats and returns the user's profile information
"""
status = "Active" if self.is_active else "Inactive"
return f"ID: {self.user_id}\nName: {self.name}\nEmail: {self.email}\nStatus: {status}"
def deactivate(self):
"""
Deactivates the user
"""
self.is_active = False
print(f"User '{self.name}' has been deactivated.")
# The part that executes the main process
if __name__ == "__main__":
# Create multiple user objects
user1 = User("web-creator", "Taro Tanaka", "tanaka@example.com")
user2 = User("designer-sato", "Hanako Sato", "sato@example.com")
# Display the profiles
print("--- User List ---")
print(user1.get_profile())
print("-" * 20)
print(user2.get_profile())
print("\n" + "=" * 20 + "\n")
# Let's try deactivating one user
user2.deactivate()
print("\n--- User List After Changes ---")
print(user1.get_profile())
print("-" * 20)
print(user2.get_profile())
When you run this code, your terminal should display the following:
Example Output:
--- User List ---
ID: web-creator
Name: Taro Tanaka
Email: tanaka@example.com
Status: Active
--------------------
ID: designer-sato
Name: Hanako Sato
Email: sato@example.com
Status: Active
====================
User 'Hanako Sato' has been deactivated.
--- User List After Changes ---
ID: web-creator
Name: Taro Tanaka
Email: tanaka@example.com
Status: Active
--------------------
ID: designer-sato
Name: Hanako Sato
Email: sato@example.com
Status: Inactive
What do you think? By using classes, user information and its related operations (like deactivation) are neatly bundled, which you can probably feel makes the code easier to read.
Things to Watch Out For / Common Mistakes
Finally, let's introduce a few points where beginners often stumble when working with classes.
- Forgetting `self`: If you forget to write `self` as the first argument when defining a method, or forget to add `self.` (like `self.name`) when accessing an attribute within a method, you will get an error. Remember the rule: "Inside a class, go through `self`."
- Misspelling `__init__`: `__init__` has two underscores before and after. If you write it with one, like `_init_`, it will be interpreted as a regular method and won't be called automatically as an initializer.
- Forgetting the `()` during instantiation: If you forget the parentheses like `my_dog = Dog`, you won't create an object. Instead, the class itself will be assigned to the variable. Always include the parentheses, like `my_dog = Dog()`.
To the Next Step
Now that you understand the basics of classes and object-oriented programming, let's try using Python's useful standard libraries. Handling dates and times is a very common task in programming.
In the next article, we will learn how to get the current date and perform date calculations using the `datetime` module.
β How to Handle Dates and Times with the datetime Module