Select Language

AI Technology Community

7.8、Pythonクラス方法の使用

クラスメソッドも特定のオブジェクトに属さないため、その最初の引数はselfではありません。しかし、それは特定のクラスに属するため、最初の引数は必ずclsです。

@classmethod
def static_func(cls, 引数リスト):
    pass

使用する際に最初の引数clsを指定する必要はありません。なぜなら、この関数には暗黙的な属性__self__があり、それがclsの値となるからです。

>>> class Student:                             # クラスを定義する
...     highest_score = 0
...     lowest_score = 100
...     def __init__(self):                    # 初期化関数
...         self.name = ""
...     @classmethod                           # クラスメソッド
...     def get_highest_score(cls):
...         print("cls = ", cls)
...         return Student.highest_score
...     def set_score(self, score):             # 通常のメンバー関数
...         if score > Student.highest_score:
...             Student.highest_score = score
...         if score < Student.lowest_score:
...             Student.lowest_score = score
...                                       # クラス定義終了
>>> student_a = Student()
>>> student_b = Student()
>>> student_c = Student()
>>> student_a.set_score(98)
>>> student_b.set_score(92)
>>> student_c.set_score(95)
>>> Student.get_highest_score()
('type = ', <class __main__.Student at 0x1047a7a78>)
98
>>> Student                                # クラスオブジェクト
<class __main__.Student at 0x1047a7a78>    # 関数の属性__self__はクラスオブジェクト
>>> student_a.get_highest_score.__self__
<class __main__.Student at 0x1047a7a78>


post
  • 10

    item of content
前の章では、リストや辞書などのPythonの予め定義されたデータ型について説明しました。しかし、自分で新しいタイプを定義したい場合、クラスを使用する必要があります。つまり、クラスを使用することで自分だけのデータ型を定義でき、システムで定義された型だけを使う以上のことができます。
クラスはオブジェクト指向プログラミングにおいて非常に基本的な概念であり、最も基本的な機能は新しいデータ型を作成することです。さらに、クラスAから新しいクラスBを派生させることができ、その際クラスBはクラスAのすべての属性を継承します(これを継承機能と呼びます)。
この章では、クラスの定義と使用方法について説明します。具体的には、クラスのプロパティとメソッド、クラスの派生方法、多重継承の使用方法などを解説します。