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

Understanding SentencePiece: A Language-Independent Tokenizer for AI Engineers

In the realm of Natural Language Processing (NLP), tokenization plays a pivotal role in preparing text data for machine learning models. Traditional tokenization methods often rely on language-specific rules and pre-tokenized inputs, which can be limiting when dealing with diverse languages and scripts. Enter SentencePiece—a language-independent tokenizer and detokenizer designed to address these challenges and streamline the preprocessing pipeline for neural text processing systems. What is SentencePiece? SentencePiece is an open-source tokenizer and detokenizer developed by Google, tailored for neural-based text processing tasks such as Neural Machine Translation (NMT). Unlike conventional tokenizers that depend on whitespace and language-specific rules, SentencePiece treats the input text as a raw byte sequence, enabling it to process languages without explicit word boundaries, such as Japanese, Chinese, and Korean. This approach allows SentencePiece to train subword models di...

Mastering the Byte Pair Encoding (BPE) Tokenizer for NLP and LLMs

Byte Pair Encoding (BPE) is one of the most important and widely adopted subword tokenization algorithms in modern Natural Language Processing (NLP), especially in training Large Language Models (LLMs) like GPT. This guide provides a deep technical dive into how BPE works, compares it with other tokenizers like WordPiece and SentencePiece, and explains its practical implementation with Python code. This article is optimized for AI engineers building real-world models and systems. 1. What is Byte Pair Encoding? BPE was originally introduced as a data compression algorithm by Gage in 1994. It replaces the most frequent pair of bytes in a sequence with a single, unused byte. In 2015, Sennrich et al. adapted BPE for NLP to address the out-of-vocabulary (OOV) problem in neural machine translation. Instead of working with full words, BPE decomposes them into subword units that can be recombined to represent rare or unseen words. 2. Why Tokenization Matters in LLMs Tokenization is th...

Using Gemini API in LangChain: Step-by-Step Tutorial

What is LangChain and Why Use It? LangChain  is an open-source framework that simplifies the use of  Large Language Models (LLMs)  like OpenAI, Gemini (Google), and others by adding structure, tools, and memory to help build real-world applications such as chatbots, assistants, agents, or AI-enhanced software. Why Use LangChain for LLM Projects? Chainable Components : Easily build pipelines combining prompts, LLMs, tools, and memory. Multi-Model Support : Work with Gemini, OpenAI, Anthropic, Hugging Face, etc. Built-in Templates : Manage prompts more effectively. Supports Multi-Turn Chat : Manage complex interactions with memory and roles. Tool and API Integration : Let the model interact with external APIs or functions. Let's Walk Through the Code: Gemini + LangChain I will break the code into  4 main parts , each showcasing different features of LangChain and Gemini API. Part 1: Basic Gemini API Call Using LangChain import os from dotenv import load_dotenv load_dot...