AI Technology Community
7.6、Python静的方法の使用
静的メソッドとは、特定のオブジェクトにバインドされていないメソッドです。オブジェクトメソッドと異なり、定義時の最初の引数が self ではなく、通常の関数に似ています。self 引数がないため、「self.属性名」を使用して特定のオブジェクトの属性にアクセスすることもできません。
静的メソッドの定義形式は次の通りです。
@staticmethod def static_func(): pass
Student クラスでは、最低成績と最高成績を取得する処理は静的メソッドで実装するのが適しています。これらの関数は学生オブジェクトのデータを操作する必要がないからです。以下のコードのようになります。
>>> class Student: # クラス Student を定義する
... highest_score = 0 # クラス属性
... lowest_score = 100
... def __init__(self): # 初期化関数
... self.name = ""
... @staticmethod # 静的メソッドを定義する。最初の引数は self ではない
... def get_highest_score():
... 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_a.set_score(98) # 通常のメソッド
>>> student_b = Student()
>>> student_b.set_score(90)
>>> student_c = Student()
>>> student_c.set_score(92)
>>> Student.get_highest_score() # 静的メソッド
98
10
item of content
クラスはオブジェクト指向プログラミングにおいて非常に基本的な概念であり、最も基本的な機能は新しいデータ型を作成することです。さらに、クラスAから新しいクラスBを派生させることができ、その際クラスBはクラスAのすべての属性を継承します(これを継承機能と呼びます)。
この章では、クラスの定義と使用方法について説明します。具体的には、クラスのプロパティとメソッド、クラスの派生方法、多重継承の使用方法などを解説します。
- 479hits
- 0replay
-
0like
- collect
- send report