Python Class Methods: Complete Guide, Usage & Examples

目次

1. What Is a Python Class Method? A Clear Explanation from the Basics

Python has a mechanism called “class method,” which is used when defining methods that operate on the entire class. Class methods are used to operate on the class itself rather than on a specific instance (object). This article will provide a detailed explanation of class methods from the basics to their usage and applications.

1.1 What Is a Python Class Method?

A class method is defined using Python’s @classmethod decorator and is characterized by receiving the class itself as its first argument. While regular instance methods take self as the first argument, class methods take cls (short for class) as the argument. Using this cls allows you to access class variables and manipulate the class itself.

1.2 Features of Class Methods

Class methods have the following characteristics.
  1. Can be called without creating an instance
  • Regular instance methods cannot be called unless you create an instance of the class. However, class methods can be called directly from the class without creating an instance.
  1. Can manipulate class variables
  • Class methods can directly manipulate variables that belong to the class (class variables), making it easier to manage data common to all instances.
  1. Used as factory methods
  • Class methods are often used as factory methods that create class instances based on specific data.

1.3 Benefits of Learning Class Methods

Understanding and using Python class methods provides the following benefits. ✅ Deepens understanding of object-oriented programmingImproves code reusabilityEnables efficient management of class variables

1.4 Prerequisite Knowledge for Understanding Class Methods

1.4.1 Python Classes and Objects

Python adopts object-oriented programming (OOP) and builds code using the concept of “classes.”
class Car:
    def __init__(self, brand):
        self.brand = brand  # instance variable

my_car = Car("Toyota")
print(my_car.brand)  # Toyota

1.4.2 Difference Between self and cls

When understanding class methods, the difference between self and cls is a crucial point.
KeywordRoleWhere Used?
selfReferences the instance (object)Instance method
clsReferences the class itselfClass method
Let’s look at the following example.
class Example:
    class_variable = "Class variable"

    def instance_method(self):
        return "This is an instance method"

    @classmethod
    def class_method(cls):
        return f"Class variable value: {cls.class_variable}"

# Class method can be called without creating an instance
print(Example.class_method())  # Class variable value: Class variable

# Instance method cannot be called without creating an instance
example_instance = Example()
print(example_instance.instance_method())  # This is an instance method

1.5 Summary

  • Class methods act on the class itself
  • Defined using the @classmethod decorator and receive cls as the first argument
  • Can be called without creating an instance
  • Can be used for managing class variables and as factory methods
  • self references the instance, and cls references the class

2. Defining and Using Python Class Methods

In the previous section, we explained the basic concepts and roles of class methods. Here, we will detail how to define them and how to use them with concrete code examples.

2.1 Basic Syntax of Class Methods

To define a class method in Python, use the @classmethod decorator. Below is the basic syntax.
class ClassName:
    @classmethod
    def method_name(cls, arg1, arg2, ...):
        # method processing
        return result

Key Points for Defining Class Methods

  1. @classmethod decorator placed immediately before the method
  2. Accept cls as the first argument (cls refers to the class itself)
  3. Can access class variables and other class methods
  4. Can be called directly from the class (no instance needed)

2.2 Example Implementation of a Class Method

Let’s define a class method and see it in action.
class Sample:
    class_variable = "Class variable"

    @classmethod
    def class_method(cls):
        print(f"Class method was called. Class variable value: {cls.class_variable}")

# Call the class method
Sample.class_method()

Output

Class method was called. Class variable value: Class variable

Code Explanation

  • class_variable is defined as a class variable.
  • class_method() has the @classmethod decorator and uses cls to access class_variable.
  • Calling Sample.class_method() demonstrates that you can invoke the method directly without creating an instance.

2.3 How to Call a Class Method

Class methods can be called in two ways.

① Call Directly from the Class Name

Sample.class_method()
This is the most common way to call and can perform operations on the entire class.

② Call Through an Instance

sample_instance = Sample()
sample_instance.class_method()
In this case, the method runs via the instance, but note that cls receives the class, not the instance.

2.4 Class Methods that Manipulate Class Variables

Class methods are very handy for modifying class variables. For example, they can be used to manage version information or configuration values.
class Config:
    version = "1.0"

    @classmethod
    def update_version(cls, new_version):
        cls.version = new_version  # modify class variable

# Update version using class method
Config.update_version("2.0")
print(Config.version)  # 2.0

Explanation

  • update_version() uses cls.version to modify the class variable.
  • Calling Config.update_version("2.0") updates the version for all instances.

2.5 Creating Instances with Class Methods (Factory Methods)

Class methods can also be used as factory methods to create new instances.
class User:
    def __init__(self, name):
        self.name = name

    @classmethod
    def from_string(cls, name_str):
        return cls(name_str)  # create a new instance using cls

# Create an instance using the class method
user = User.from_string("Sato")
print(user.name)  # Sato

Explanation

  • from_string() calls cls(name_str) to create a new instance.
  • Thus it yields the same result as direct instantiation like User("Sato"), but allows preprocessing of the data.

2.6 Differences from Instance Methods

Comparing regular instance methods with class methods reveals the following differences.
Method TypeFirst ArgumentCalling MethodScope of Effect
Instance Methodselfinstance.method()Specific instance
Class MethodclsClass.method() or instance.method()Entire class
Static MethodNoneClass.method()Behaves like an independent function
Class methods are appropriately used to perform operations on the entire class without depending on an instance.

2.7 When to Use Class Methods

Class methods are useful in the following scenarios. ✅ Managing class-level data
  • Updating configuration values or counters
  • Example: Config.update_version()
Using as a factory method
  • Creating instances from specific formats
  • Example: User.from_string()
Applicable to subclasses
  • Using cls allows it to work with derived classes
class Base:
    @classmethod
    def show_class_name(cls):
        print(f"Class name: {cls.__name__}")

class Derived(Base):
    pass

Derived.show_class_name()  # Class name: Derived
In this way, you can also inherit and use a parent class’s class method as needed.

2.8 Summary

In this section, we covered how to define and use Python class methods. Let’s recap the key points.
  • Define a class method using @classmethod
  • Using cls enables access to class variables and class operations
  • Class methods can be called directly without creating an instance
  • They can also be used as factory methods for instance creation
  • Class methods are ideal for logic that affects the entire class
RUNTEQ(ランテック)|超実戦型エンジニア育成スクール

3. Python Class Method Use Cases (Practical Use Cases)

In the previous sections, we learned the basics of Python class methods and how to use them. In this section, we will explain how class methods are actually used through concrete use cases.

3.1 Typical Use Patterns for Class Methods

Class methods are especially useful in the following situations.
  1. Use as a factory method
  2. Management of configuration values and shared data
  3. Methods that modify the class state
  4. Dynamic use of classes leveraging inheritance
  5. Simplifying database connections and management
Let’s examine each case in detail, accompanied by code examples.

3.2 Use Case 1: Using as a Factory Method

A factory method is a method that creates a new in a specific format. For example, consider the following case.

Create an instance of the User class from string data

class User:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    @classmethod
    def from_string(cls, user_info):
        name, age = user_info.split(",")  # Split comma-separated string
        return cls(name, int(age))  # Create a new instance

# Create an instance using the class method
user = User.from_string("Sato,30")
print(user.name)  # Sato
print(user.age)   # 30

Benefits of this approach

  • Centralized data preprocessing can be performed
  • Improved code readability, enabling flexible instance creation
  • Easily adaptable to different data formats
For example, this pattern can also be applied when handling JSON or CSV data.

3.3 Use Case 2: Managing configuration values and shared data

Using class methods is convenient when managing configuration values shared across the entire application or mutable default values.
class Config:
    default_language = "Japanese"
    default_theme = "Light"

    @classmethod
    def update_language(cls, new_language):
        cls.default_language = new_language  # Update class variable

    @classmethod
    def update_theme(cls, new_theme):
        cls.default_theme = new_theme

# Change settings using class methods
Config.update_language("English")
Config.update_theme("Dark")

print(Config.default_language)  # English
print(Config.default_theme)     # Dark

Benefits of this approach

  • Maintain consistent settings across the entire app
  • Apply changes at the class level rather than per individual instance

3.4 Use Case 3: Methods that modify class state

Using class methods, you can manage the class state (e.g., the total number of instances).
class Counter:
    count = 0  # Class variable (shared by all instances)

    def __init__(self):
        Counter.increment_count()

    @classmethod
    def increment_count(cls):
        cls.count += 1  # Modify class variable

# Counter increments when an instance is created
c1 = Counter()
c2 = Counter()
c3 = Counter()

print(Counter.count)  # 3

Benefits of this approach

  • Manage uniform data across all instances
  • By using class methods, you can monitor the creation of new instances

3.5 Use Case 4: Dynamic use of classes leveraging inheritance

Since class methods apply to subclasses as well, you can dynamically override a parent class’s class method.
class Animal:
    species = "Unknown"

    @classmethod
    def set_species(cls, new_species):
        cls.species = new_species

class Dog(Animal):
    pass

class Cat(Animal):
    pass

# Different settings can be applied per class
Dog.set_species("Canine")
Cat.set_species("Feline")

print(Dog.species)  # Canine
print(Cat.species)  # Feline
print(Animal.species)  # Unknown (parent class value remains unchanged)

Benefits of this approach

  • Flexible data management that respects inheritance relationships
  • Allows direct reuse of parent class methods, preventing code duplication

3.6 Use Case 5: Simplifying database connections and management

In web applications and backend development, using class methods can unify database connection and data management processes.
class Database:
    connection = None

    @classmethod
    def connect(cls, db_url):
        if cls.connection is None:
            cls.connection = f"Connected to {db_url}"
        return cls.connection

# Connect to the database
db1 = Database.connect("mysql://localhost:3306/mydb")
db2 = Database.connect("mysql://localhost:3306/mydb")

print(db1)  # Connected to mysql://localhost:3306/mydb
print(db1 is db2)  # True (reusing the same connection)

Benefits of this approach

  • Unified management of database connections
  • Allows multiple instances to share the same connection (Singleton pattern)

3.7 Summary

In this section, we presented practical examples of using class methods.

Main Points

  • Use as a factory method to streamline data preprocessing and instance creation
  • Manage configuration values and shared data as class variables for easy modification
  • Use class methods that modify class state to simplify management of instance counts, etc.
  • Leverage inheritance to dynamically apply parent class methods
  • Applicable to use cases such as database connection management

4. Differences Between Class Methods and Other Methods (With Comparison Table)

Understanding Python class methods requires clearly distinguishing them from instance methods and static methods. Each method has a different role, and using them appropriately allows you to write more efficient code. In this section, we will compare and explain the differences between class methods and other methods.

4.1 The Three Types of Methods in Python

There are three types of methods that can be defined inside a Python class.
Method TypeDecoratorFirst ArgumentAccess to Class VariablesAccess to Instance VariablesCalling Method
Instance MethodNoneselfPossiblePossibleinstance.method()
Class Method@classmethodclsPossibleNot possibleClass.method() or instance.method()
Static Method@staticmethodNoneNot possibleNot possibleClass.method() or instance.method()
Based on this table, let’s take a closer look at the differences among the methods.

4.2 What Is an Instance Method?

An instance method is a method implemented to provide behavior that varies for each class instance (object). self is taken as the first argument, allowing you to manipulate instance variables (attributes).

Example of an Instance Method

class Dog:
    def __init__(self, name):
        self.name = name  # instance variable

    def bark(self):
        return f"{self.name} is barking!"

# create instances
dog1 = Dog("Pochi")
dog2 = Dog("Shiro")

print(dog1.bark())  # Pochi is barking!
print(dog2.bark())  # Shiro is barking!

Key Points

Use self to handle data specific to each instanceThe method cannot be called without creating an instance

4.3 What Is a Class Method?

A class method is a method that performs operations concerning the entire class. By taking cls as the first argument, you can directly modify or reference class variables.

Example of a Class Method

class Cat:
    species = "Felidae"

    def __init__(self, name):
        self.name = name

    @classmethod
    def set_species(cls, new_species):
        cls.species = new_species  # modify class variable

# use class method to modify class variable
Cat.set_species("Felidae")

# change is reflected in all instances
cat1 = Cat("Mickey")
cat2 = Cat("Tama")

print(cat1.species)  # Felidae
print(cat2.species)  # Felidae
print(Cat.species)   # Felidae

Key Points

Can manipulate class variables using clsConvenient when implementing logic that concerns the entire classCan be called directly with Class.method() without creating an instance

4.4 What Is a Static Method?

A static method (static method) is used to define a general-purpose function that does not depend on the class or its instances within a class. It does not take self or cls as a first argument and cannot access class or instance variables.

Example of a Static Method

class MathHelper:
    @staticmethod
    def add(x, y):
        return x + y

    @staticmethod
    def multiply(x, y):
        return x * y

# static methods can be called without creating an instance
print(MathHelper.add(3, 5))  # 8
print(MathHelper.multiply(4, 6))  # 24

Key Points

Useful when defining functions that do not use class or instance variablesCan be used like a regular function, but organized within the classCan be called without creating an instance (Class.method())

4.5 Which Method Should You Use?

The criteria for selecting the appropriate method can be summarized as follows.
Method TypeWhen to Use
Instance MethodWhen handling data that varies per instance (e.g., manipulating self.name)
Class MethodWhen performing operations that affect the entire class (e.g., modifying a class variable)
Static MethodWhen defining a general-purpose function related to the class (e.g., mathematical operations or data conversion)

4.6 Summary

In this section, we explained the differences between class methods and other methods (instance methods, static methods).

Review of Key Points

  • Instance Method
  • self is taken as the first argument and manipulates instance variables
  • Suitable when managing data that differs per instance
  • Class Method
  • cls is taken as the first argument and manipulates class variables
  • Suitable for managing or changing settings that affect the entire class
  • Static Method
  • Does not receive self or cls and performs operations independent of the class or instances
  • Suitable for functions related to the class but that do not affect specific instances or class variables

5. Frequently Asked Questions about Python Class Methods

When learning Python class methods, many people have questions. In this section, we clearly explain frequently asked questions about class methods and their answers.

5.1 Questions about the basics of class methods

Q1. When should you use a class method?

A. Class methods are used when writing operations that affect the entire class. They are especially useful in the following cases. ✅ When you want to modify a class variableWhen you want to create a factory method to generate instances from data in a specific formatWhen you need to manage the class state (such as counters or configuration values)

Q2. What is the difference between a class method and an instance method?

A. A class method uses @classmethod and receives cls as its first argument. In contrast, an instance method takes self as its first argument.
Method typeFirst argumentAccess to class variablesAccess to instance variables
Instance methodselfPossiblePossible
Class methodclsPossibleNot possible
Example (comparison)
class Sample:
    class_variable = "Class variable"

    def __init__(self, name):
        self.name = name  # instance variable

    def instance_method(self):
        return f"Instance variable: {self.name}"

    @classmethod
    def class_method(cls):
        return f"Class variable: {cls.class_variable}"

# Instance method is called via an instance
s = Sample("Taro")
print(s.instance_method())  # Instance variable: Taro

# Class method can be called directly from the class
print(Sample.class_method())  # Class variable: Class variable

Q3. Can a class method access instance variables?

A. It cannot. Class methods are meant to access class variables (cls.attribute) rather than instance variables (self.attribute). If you need to manipulate instance variables, you must use an instance method.

5.2 Questions about class methods and static methods

Q4. What is the difference between a class method and a static method?

A. A class method (@classmethod) receives cls and can manipulate class variables. In contrast, a static method (@staticmethod) does not receive self or cls and does not depend on the class or an instance.
Method typeFirst argumentAccess to class variablesAccess to instance variables
Class methodclsPossibleNot possible
Static methodNoneNot possibleNot possible
Example (comparison)
class Example:
    class_variable = "Class variable"

    @classmethod
    def class_method(cls):
        return f"Class variable value: {cls.class_variable}"

    @staticmethod
    def static_method():
        return "Static methods cannot handle class variables"

# Class method
print(Example.class_method())  # Class variable value: Class variable

# Static method
print(Example.static_method())  # Static methods cannot handle class variables

Q5. When should you use a static method?

A. Static methods are used to define general-purpose functions that do not depend on the class or an instance. For example, mathematical operations or data format conversion functions.
class MathUtils:
    @staticmethod
    def add(a, b):
        return a + b

print(MathUtils.add(3, 7))  # 10

5.3 Practical questions about class methods

Q6. Can you create an instance using a class method?

A. Yes, you can. Class methods can be used as factory methods, which are handy for creating instances from external data (strings, JSON, database records, etc.).
class User:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    @classmethod
    def from_string(cls, user_data):
        name, age = user_data.split(",")
        return cls(name, int(age))

# Create instance from string
user = User.from_string("Sato,30")
print(user.name)  # Sato
print(user.age)   # 30

Q7. Does the usage of class methods change with different Python versions?

A. The basic usage does not change. In Python 2.x, classmethod() was sometimes used instead of @classmethod, but Python 3.x and later recommend using @classmethod. Also, starting with Python 3.9, you can use type hinting.
class Sample:
    class_variable: str = "Class variable"

    @classmethod
    def get_class_variable(cls) -> str:
        return cls.class_variable

5.4 Summary

In this section, we presented frequently asked questions about class methods and their answers.

Key points

  • Class methods are suitable for managing the entire class
  • Class methods cannot access instance variables
  • Understand the difference between class methods and static methods and use them appropriately
  • As factory methods, they can create instances from data
  • The basic usage does not change across Python versions, but type hinting can be utilized

6. Summary (Deepening Your Understanding of Class Methods)

So far, we have provided a detailed explanation of Python class methods, covering everything from basic concepts to practical usage. In this section, we review what we’ve covered and organize key points to deepen your understanding of class methods.

6.1 Key Takeaways for Class Methods

The main points you’ve learned about Python class methods are as follows.

Basics of Class Methods

  • @classmethod Define using the decorator
  • Accepts cls as the first argument, allowing you to reference and modify the entire class
  • Can be called with Class.method() without creating an instance

Practical Uses of Class Methods

  • Used as a factory method → Generate instances from strings or JSON data
  • Managing configuration values and class variables → Change application-wide settings, e.g., Config.update_language()
  • Managing overall class state → Used for tracking total instance count or versioning
  • Dynamic class design leveraging inheritance → Provide different behavior for each subclass

Differences from Instance and Static Methods

Method TypeDecoratorFirst ArgumentClass Variable AccessInstance Variable AccessInvocation
Instance MethodNoneselfYesYesinstance.method()
Class Method@classmethodclsYesNoClass.method() or instance.method()
Static Method@staticmethodNoneNoNoClass.method() or instance.method()

6.2 When to Use Class Methods

Using Python class methods appropriately improves code readability and maintainability. In the following situations, it’s beneficial to actively use class methods. 📌 Want to standardize instance creation → Implement factory methods such as from_string() to achieve consistent instance creation 📌 Need a method to manipulate class variables → Useful for updating settings, e.g., Config.update_theme() 📌 Want to leverage parent class functionality in subclasses → Using cls ensures proper behavior across inheritance hierarchies

6.3 Deepening Your Understanding of Class Methods

To further deepen your grasp of class methods, try the following approaches. 1️⃣ Write and test code yourself → Create a simple class that uses class methods and observe its behavior 2️⃣ Explore examples in other projects → Class methods are commonly used in frameworks like Django and Flask 3️⃣ Compare with static and instance methods → Consider which method type is appropriate for each scenario during design

6.4 Summary

This article provided an in‑depth explanation of Python class methods. ✔ Understand the basics and role of class methods ✔ Learn practical applications and use them in the right contexts ✔ Grasp the differences from instance and static methods and be mindful of when to use each When you master Python class methods, you’ll be able to write more efficient and maintainable code. Feel free to apply what you’ve learned to your own programs!