PYTHON MEBY

Pythonで静的メソッド・クラスメソッドを使う(@staticmethod, @classmethod)

この記事では、Pythonにおける静的メソッドとクラスメソッドについて解説します。@staticmethodと@classmethodデコレータの使い方、それぞれの用途、そして具体的なコード例を通して理解を深めます。

目次

静的メソッド (@staticmethod)

静的メソッドは、クラスに属していますが、インスタンスやクラス自身にアクセスしません。インスタンスやクラスの状態に依存しない、独立したユーティリティ関数として使用できます。

class MyClass:
    @staticmethod
    def static_method(a, b):
        return a + b

result = MyClass.static_method(5, 3)
print(result)  # Output: 8

@staticmethodデコレータを使用して定義します。第一引数にselfもclsも渡しません。

クラスメソッド (@classmethod)

クラスメソッドは、クラス自身にアクセスできますが、インスタンスにはアクセスできません。クラスの状態を変更したり、クラスファクトリとして利用したりします。

class MyClass:
    count = 0

    def __init__(self):
        MyClass.count += 1

    @classmethod
    def get_count(cls):
        return cls.count

instance1 = MyClass()
instance2 = MyClass()
print(MyClass.get_count())  # Output: 2

@classmethodデコレータを使用して定義します。第一引数にcls(クラス自身)が渡されます。

静的メソッドとクラスメソッドの違い

静的メソッドはクラスに属する独立した関数、クラスメソッドはクラスの状態にアクセスできる関数です。インスタンスの状態に依存しないユーティリティ関数は静的メソッド、クラスの状態を操作する関数はクラスメソッドとして定義するのが一般的です。

使用例:シンプルなカウンター

クラスメソッドを使って、クラスのインスタンス数をカウントする例です。

class Counter:
    _instances = 0  # クラス変数でインスタンス数を保持

    def __init__(self):
        Counter._instances += 1

    @classmethod
    def get_instance_count(cls):
        return cls._instances

counter1 = Counter()
counter2 = Counter()
print(Counter.get_instance_count()) # Output: 2

使用例:ユーティリティ関数

静的メソッドを使って、クラスとは独立したユーティリティ関数を実装する例です。

class MathUtils:
    @staticmethod
    def is_even(number):
        return number % 2 == 0

print(MathUtils.is_even(4))  # Output: True
print(MathUtils.is_even(7))  # Output: False

関連記事