@propertyデコレーション

1470 ワード

  • Python内蔵の@propertyデコレーションは、一つの方法を、属性のように、値を取ることができる
  • に変えます.
  • @score.setter,一つの方法を,属性のように付与できるようにする
  • @propertyとscore.setter()は同時に、読み書き可能
  • を表す.
  • @propertyのみ、読み取り専用
  • を表します
  • 以下のscore()自体が一つの方法であり、本来の使い方はs.score()
  • である
  • @property経由で、属性のようにs.score、括弧なし
  • class Student(object):
    
        @property
        def score(self):
            return self._score
    
        @score.setter
        def score(self, value):
            if not isinstance(value, int):
                raise ValueError('score must be an integer!')
            if value < 0 or value > 100:
                raise ValueError('score must between 0 ~ 100!')
            self._score = value
    s = Student()
    s.score = 60 # OK,     s.set_score(60)
    s.score # OK,     s.get_score()
    

    練習:@propertyを使用してScreenオブジェクトにwidthとheightプロパティと読み取り専用プロパティresolutionを追加してください.
    class Screen(object):
        @property
        def width(self):
            return self._width
        @width.setter
        def width(self,value):
            self._width=value
        @property
        def height(self):
            return self._height
        @height.setter
        def height(self,value):
            self._height=value
        @property
        def resolution(self):
            self._resolution=self._width*self._height
            return self._resolution
    
    s = Screen()
    s.width = 1024
    s.height = 768
    print('resolution =', s.resolution)
    if s.resolution == 786432:
        print('    !')
    else:
        print('    !')