2018년 4월 9일 월요일

[python] property 알기

# property

class Square(object):
  def __init__(self, side):
    self.side = side
  def aget(self):
    return self.side ** 2
  def aset(self, value):
    print('no')
  def adel(self, value):
    print('no')
  area = property(aget, aset, adel, doc='area') # 이게 중요!!
  
s = Square(5)
print(s.area)



"""Properties with decorators.
데코레이터를 사용하게 된다. 위에 내용과 같다.
"""

from __future__ import print_function

class Square(object):
    """A square using properties with decorators.
    """
    def __init__(self, side):
        self.side = side
    @property
    def area(self):
        """Calculate the area of the square when the
        attribute is accessed."""
        return self.side * self.side
    @area.setter
    def area(self, value):
        """Don't allow setting."""
        print("Can't set the area")
    @area.deleter
    def area(self):
        """Don't allow deleting."""
        print("Can't delete the area.")

if __name__ == '__main__':

    square = Square(5)
    print('area:', square.area)
    print('try to set')
    square.area = 10
    print('area:', square.area)
    print('try to delete')
    del square.area
    print('area:', square.area)

댓글 없음 :

댓글 쓰기