프로퍼티 데코레이터
Coddy Python 여정의 Object Oriented Programming 섹션에 포함된 레슨 — 64개 중 10번째.
@property 데코레이터는 메서드를 속성처럼 액세스할 수 있게 해주어, 값을 가져오고 설정하는 깔끔한 방법을 제공합니다.
다음은 @property를 사용하는 클래스의 예입니다:
class Circle:
def __init__(self, radius):
self._radius = radius
@property
def radius(self):
return self._radius
@property
def area(self):
return 3.14159 * self._radius ** 2원을 생성하고 속성에 액세스합니다:
my_circle = Circle(5)일반 속성처럼 프로퍼티에 접근합니다:
print(my_circle.radius)
print(my_circle.area)출력:
5
78.53975프로퍼티에 접근할 때 괄호 ()를 사용하지 않는다는 점에 유의하세요. 속성처럼 보이지만 메서드 코드를 실행합니다.
값을 변경할 수 있도록 setter를 추가합니다:
class Circle:
def __init__(self, radius):
self._radius = radius
@property
def radius(self):
return self._radius
@radius.setter
def radius(self, value):
if value > 0:
self._radius = value
else:
print("Radius must be positive!")이제 반지름(radius)을 속성처럼 설정할 수 있습니다:
my_circle = Circle(5)
my_circle.radius = 10 # setter를 사용합니다
print(my_circle.radius) # getter를 사용합니다출력:
10핵심 포인트: @property는 메서드를 속성처럼 보이게 만들며, @property_name.setter는 값이 할당되는 방식을 제어할 수 있게 해줍니다.
치트 시트
@property 데코레이터를 사용하면 메서드를 속성처럼 액세스할 수 있어, 값을 가져오고 설정하는 깔끔한 방법을 제공합니다.
기본적인 프로퍼티 사용법:
class Circle:
def __init__(self, radius):
self._radius = radius
@property
def radius(self):
return self._radius
@property
def area(self):
return 3.14159 * self._radius ** 2괄호 없이 프로퍼티에 액세스하기:
my_circle = Circle(5)
print(my_circle.radius) # 5
print(my_circle.area) # 78.53975값 할당을 제어하기 위해 setter 추가하기:
@radius.setter
def radius(self, value):
if value > 0:
self._radius = value
else:
print("Radius must be positive!")속성처럼 값 설정하기:
my_circle.radius = 10 # setter를 사용합니다
print(my_circle.radius) # getter를 사용합니다직접 해보기
이 레슨에는 코드 챌린지가 없습니다.
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.