class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
def __repr__(self):
return f'Rectangle({self.width}, {self.height})'
r1 = Rectangle(10, 20)
r1 # Rectangle(10, 20)
파이썬에서는 해당 property에 직접 접근하여 값을 바꾸는 것을 좋아하지 않음
→ 클래스 안에서 쓸 변수들은 앞에 언더바(_)를 붙인다 → private variable
class Rectangle:
def __init__(self, width, height):
self._width = width
self._height = height
def area(self):
return self._width * self._height
def __repr__(self):
return f'Rectangle({self._width}, {self._height})'
r1 = Rectangle(10, 20)
r1 # Rectangle(10, 20)
private variable 값을 바꿀 땐 어떻게 해야 할까?
class Rectangle:
def __init__(self, width, height):
self._width = width
self._height = height
def get_width(self):
return self._width
def set_width(self, width):
if width <= 0:
raise ValueError('Width must be positive')
else:
self._width = width
def get_height(self):
return self._height
def set_height(self, height):
if height <= 0:
raise ValueError('Height must be positive')
else:
self._height = height
def area(self):
return self._width * self._height
def __repr__(self):
return f'Rectangle({self._width}, {self._height})'
r1 = Rectangle(10, 20)
r1.set_height(5)
여기서 set, get 메소드가 아닌 property 형태로 사용할 수 있는 것이 데코레이터의 기능
class Rectangle:
def __init__(self, width, height):
self._width = width
self._height = height
@property
def width(self):
return self._width
@width.setter
def width(self, width):
print('setter가 실행되었습니다.')
if width <= 0:
raise ValueError('Width must be positive')
else:
self._width = width
@property
def height(self):
return self._height
@height.setter
def height(self, height):
if height <= 0:
raise ValueError('Height must be positive')
else:
self._height = height
def area(self):
return self.width * self.height
def __repr__(self):
return f'Rectangle({self.width}, {self.height})'
r1 = Rectangle(10, 20)
r1.width = 5
r1 # Rectangle(5, 20)