python の @property が果たす役割
あるメソッドを、読取専用のアトリビュートにする。
class Point: def __init__(self, point_x, point_y): self._point_x = point_x self._point_y = point_y @property def point_x(self): return self._point_x @property def point_y(self): return self._point_y p = Point(10, 33) print(p.point_x) #=> 10 print(p.point_y) #=> 33
冒頭の定義に従えば、@property に使うメソッド名は変数名に寄せなくてもよい。
class Point: def __init__(self, point_x, point_y): self._point_x = point_x self._point_y = point_y @property def tell_me_the_x(self): return self._point_x @property def what_is_y(self): return self._point_y p = Point(10, 33) print(p.tell_me_the_x) #=> 10 print(p.what_is_y) #=> 33
参考記事: