Python supports “Object-Oriented Programming.” Until now, we have used standard data types like lists and dictionaries. However, as programs grow larger, you often want to manage related data (variables) and the processing (functions) that manipulate them as a single unit.
This is achieved by the Class. By defining a class, you can create your own custom data structures (objects). This article explains the basic flow: class definition, constructors, methods, and instantiation.
Basics of Classes and Objects
- Class: A “blueprint” that groups data and functions. It defines what information (attributes) it holds and what actions (methods) it can perform.
- Instance / Object: An “entity” created based on the class (blueprint).
How to Define a Class
Use the class keyword to define a class. As an example, let’s create a Product class to manage items on an e-commerce site. This class holds data for the product name and price, and has functions to display information and apply discounts.
class Product:
"""
Class to manage products
"""
def __init__(self, name, price):
"""
Constructor (Initialization method)
Called when an instance is created to set attributes
"""
self.name = name # Product Name
self.price = price # Price
def show_detail(self):
"""
Method to display product details
"""
print(f"Product: {self.name} | Price: {self.price} yen")
def apply_discount(self, rate):
"""
Method to accept discount rate and update price
"""
discount_amount = int(self.price * rate)
self.price -= discount_amount
print(f"Applied {int(rate * 100)}% discount.")
# --- Using the Class (Instantiation) ---
# Generate concrete product data (instances) from the Product class
laptop = Product("Gaming Laptop", 150000)
mouse = Product("Wireless Mouse", 3000)
# Access attributes (data)
print(f"Created Product: {laptop.name}")
# Call methods (functions)
laptop.show_detail()
mouse.show_detail()
print("-" * 20)
# Execute discount method
# Apply 10% (0.1) discount
laptop.apply_discount(0.1)
# Check if the price has changed
laptop.show_detail()
Output:
Created Product: Gaming Laptop
Product: Gaming Laptop | Price: 150000 yen
Product: Wireless Mouse | Price: 3000 yen
--------------------
Applied 10% discount.
Product: Gaming Laptop | Price: 135000 yen
Explanation of the Code
1. Constructor __init__
def __init__(self, name, price):
self.name = name
self.price = price
__init__ is a special method that is automatically called when an instance (entity) is created from a class. This is called the “Constructor.” By writing self.variable_name = value here, you save data unique to that instance (attributes/instance variables).
2. What is self?
The first argument self in a method refers to “the instance itself that is calling the method.” When you call laptop.show_detail(), self inside the show_detail method refers to the laptop data. This allows laptop and mouse created from the same class to hold different names and prices.
3. Instantiation and Usage
laptop = Product("Gaming Laptop", 150000)
You create a new instance by calling the class name with () parentheses. The arguments are passed to the __init__ method (self is passed automatically, so you do not need to write it).
Summary
- Define a custom type with
class ClassName:. - Perform initialization (saving data) during instance creation with the
__init__method. - Access data and methods for each instance through
self.
Grouping data and processing into classes helps organize code and makes large-scale program development easier.
