LoginSignup
14
17

More than 5 years have passed since last update.

Pythonのプロパティ宣言

Posted at

Pythonでも、C#等によく似たプロパティを扱えます。
C#を例として見ていきます。

例:C#のプロパティ

Exam.cs
public class Exam {
    private int _mathGrade;

    public int MathGrade {
        get { return _mathGrade; }
        set { 
            if (value < 0 || 100 < value) {
                throw new ArgumentOutOfRangeException("Grade must be between 0 and 100");
            }
            _mathGrade = value;
         }
    }
}

Pythonのプロパティ

Exam.py
class Exam(object):
    """試験結果"""

    def __init__(self):
        """コンストラクタ"""
        self._math_grade = 0

    @property
    def math_grade(self):
        """数学"""
        return self._math_grade

    @math_grade.setter
    def math_grade(self, value):
        if not (0 <= value <= 100):
            raise ValueError("Grade must be between 0 and 100")
        self._math_grade = value

    # 以下省略

一見、math_gradeという関数が二つあるように見えます。
しかし、プロパティのgetterに相当する処理に@propertyアノテーション、setterに相当する処理に@[プロパティ名].setterアノテーションを付与すると、それらを一体として、プロパティとして扱ってくれます。

上記のソースだと、math_gradeというプロパティが、Examクラスにある状態になります。

使い方

C#とほとんど同じです。

Main.py
exam = Exam()
exam.math_grade = 60
print(exam.math_grade) # 60と出力

クラス辞書を出力

Exam.__dict__で、Examクラスの辞書を出力すると、

{
…省略
'math_grade': <property object at 0x0000019E44954E08>,
…省略

のように、プロパティとして扱われていることがわかります。

インスタンス辞書を出力

{'_math_grade': 60}

となります。

インスタンスには、プロパティが現れない動作をします。

C#との違い

  • プロパティは、アノテーションで区別して宣言する
  • プロパティ自体は、クラスの属性(インスタンスの属性ではない)として宣言される

クラスの属性として宣言される部分は、別途説明します。

14
17
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
17