Skip to main content

The Ultimate Guide to Python Classes

Introduction

In Python, classes are the cornerstone of object-oriented programming (OOP). They allow developers to encapsulate data and functionality together, building reusable, modular, and maintainable codebases. In this guide, we will deeply explore Python classes — from basic syntax to advanced features — with fully working code examples, perfect for intermediate and advanced Python developers.

    What is a Python Class?

    class in Python is a blueprint for creating objects. It bundles data (attributes) and methods (functions) that operate on the data into one single unit.

    Basic Structure of a Class

    class ClassName:
        def __init__(self, parameters):
            self.attribute = value
    
        def method(self, parameters):
            # method body
            pass
    • __init__() is a special method called the constructor, automatically invoked when creating an instance.
    • 'self' refers to the instance itself and must always be the first parameter in instance methods.

    How to Define and Use Python Classes

    1. Defining a Class and Creating Instances

    class Dog:
        def __init__(self, name, age):
            self.name = name
            self.age = age
    
        def bark(self):
            print(f"{self.name} is barking. Woof!")
    
    # 인스턴스 생성
    dog1 = Dog("Coco", 3)
    dog1.bark()

    Output:

    Coco is barking! Woof!

    2. Instance Variables vs Class Variables

    class Car:
        wheels = 4  # Class variable
    
        def __init__(self, brand):
            self.brand = brand  # Instance variable
    
    car1 = Car("Tesla")
    car2 = Car("BMW")
    
    print(car1.brand)   # Tesla
    print(car2.brand)   # BMW
    print(car1.wheels)  # 4
    • Instance Variables: Unique to each object
    • Class Variables: Shared across all instances

    3. Types of Methods: Instance, Class, and Static Methods

    Instance Methods (default)

    class Example:
        def instance_method(self):
            print(f"Called by {self}")
    
    ex = Example()
    ex.instance_method()


    Class Methods (@classmethod)

    class Example:
        count = 0
    
        def __init__(self):
            Example.count += 1
    
        @classmethod
        def get_count(cls):
            return cls.count
    
    print(Example.get_count())  # 0
    ex1 = Example()
    ex2 = Example()
    print(Example.get_count())  # 2
    • 'cls' points to the class itself, not an instance.

    Static Methods (@staticmethod)

    class Math:
        @staticmethod
        def add(x, y):
            return x + y
    
    print(Math.add(3, 7))  # 10
    • Static methods don't need access to class or instance attributes and are great for utility functions.

    Essential Features of Python Classes

    1. Inheritance

    class Animal:
        def speak(self):
            print("The animal makes a sound.")
    
    class Dog(Animal):
        def speak(self):
            print("The dog barks! Woof!")
    
    d = Dog()
    d.speak() 
    • Inheritance lets a new class reuse methods and properties from an existing class.
    • Child classes can override parent class methods.

    2. Multiple Inheritance

    class Father:
        def gardening(self):
            print("Father is gardening.")
    
    class Mother:
        def cooking(self):
            print("Mother is cooking.")
    
    class Child(Father, Mother):
        def play(self):
            print("Child is playing.")
    
    c = Child()
    c.gardening()
    c.cooking()
    c.play()

    3. Encapsulation

    class Account:
        def __init__(self, balance):
            self.__balance = balance  # private variable
    
        def deposit(self, amount):
            self.__balance += amount
    
        def get_balance(self):
            return self.__balance
    
    acc = Account(1000)
    acc.deposit(500)
    print(acc.get_balance())  # 1500
    • Prefixing variables with __ makes them private to the class.
    • Access is controlled through getter/setter methods.

    4. Abstraction

    from abc import ABC, abstractmethod
    
    class Animal(ABC):
        @abstractmethod
        def move(self):
            pass
    
    class Bird(Animal):
        def move(self):
            print("Birds fly in the sky.")
    
    b = Bird()
    b.move()
    • Using abstract classes via the abc module allows you to define methods that must be implemented by subclasses.

    Complete Example: User Management System

    class User:
        user_count = 0  # Class variable to track number of users
    
        def __init__(self, username, email):
            self.username = username
            self.email = email
            User.user_count += 1
    
        def display_info(self):
            print(f"Username: {self.username}, Email: {self.email}")
    
        @classmethod
        def total_users(cls):
            print(f"Total users: {cls.user_count}")
    
        @staticmethod
        def validate_email(email):
            return "@" in email
    
    # 테스트
    if __name__ == "__main__":
        if User.validate_email("test@example.com"):
            user1 = User("testuser", "test@example.com")
            user1.display_info()
        
        user2 = User("anotheruser", "another@example.com")
        user2.display_info()
    
        User.total_users()
    Output:
    Username: testuser, Email: test@example.com
    Username: anotheruser, Email: another@example.com
    Total users: 2

    This example uses instance variables, class variables, class methods, static methods, and a validation pattern — a real-world mini application!

    References

    • Python Official Documentation - Classes

Comments

Popular

Building an MCP Agent with UV, Python & mcp-use

Model Context Protocol (MCP) is an open protocol designed to enable AI agents to interact with external tools and data in a standardized way. MCP is composed of three components: server , client , and host . MCP host The MCP host acts as the interface between the user and the agent   (such as Claude Desktop or IDE) and plays the role of connecting to external tools or data through MCP clients and servers. Previously, Anthropic’s Claude Desktop was introduced as a host, but it required a separate desktop app, license, and API key management, leading to dependency on the Claude ecosystem.   mcp-use is an open-source Python/Node package that connects LangChain LLMs (e.g., GPT-4, Claude, Groq) to MCP servers in just six lines of code, eliminating dependencies and supporting multi-server and multi-model setups. MCP Client The MCP client manages the MCP protocol within the host and is responsible for connecting to MCP servers that provide the necessary functions for the ...

How to Save and Retrieve a Vector Database using LangChain, FAISS, and Gemini Embeddings

How to Save and Retrieve a Vector Database using LangChain, FAISS, and Gemini Embeddings Efficient storage and retrieval of vector databases is foundational for building intelligent retrieval-augmented generation (RAG) systems using large language models (LLMs). In this guide, we’ll walk through a professional-grade Python implementation that utilizes LangChain with FAISS and Google Gemini Embeddings to store document embeddings and retrieve similar information. This setup is highly suitable for advanced machine learning (ML) and deep learning (DL) engineers who work with semantic search and retrieval pipelines. Why Vector Databases Matter in LLM Applications Traditional keyword-based search systems fall short when it comes to understanding semantic meaning. Vector databases store high-dimensional embeddings of text data, allowing for approximate nearest-neighbor (ANN) searches based on semantic similarity. These capabilities are critical in applications like: Question Ans...

RF-DETR: Overcoming the Limitations of DETR in Object Detection

RF-DETR (Region-Focused DETR), proposed in April 2025, is an advanced object detection architecture designed to overcome fundamental drawbacks of the original DETR (DEtection TRansformer) . In this technical article, we explore RF-DETR's contributions, architecture, and how it compares with both DETR and the improved model D-FINE . We also provide experimental benchmarks and discuss its real-world applicability. RF-DETR Architecture diagram for object detection Limitations of DETR DETR revolutionized object detection by leveraging the Transformer architecture, enabling end-to-end learning without anchor boxes or NMS (Non-Maximum Suppression). However, DETR has notable limitations: Slow convergence, requiring heavy data augmentation and long training schedules Degraded performance on low-resolution objects and complex scenes Lack of locality due to global self-attention mechanisms Key Innovations in RF-DETR RF-DETR intr...