Property 데코레이터
Coddy Python 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨. 64개 중 14번째.
Property 데코레이터를 사용하면 간단한 attribute 구문을 유지하면서 attribute에 액세스하고 수정하는 방식을 제어할 수 있습니다.
다음은 property getter가 있는 클래스의 예시입니다:
class Person:
def __init__(self, name, age):
self._name = name
self._age = age
@property
def age(self):
return self._ageproperty를 일반 attribute처럼 사용하세요:
person = Person("Alice", 30)
print(person.age)출력:
30실제로는 메서드를 호출하는 것이지만, 괄호 없이 age에 Access하는 것에 주목하세요.
값을 설정할 때 데이터를 validation하기 위한 setter를 추가하세요:
class Person:
def __init__(self, name, age):
self._name = name
self._age = age
@property
def age(self):
return self._age
@age.setter
def age(self, value):
if value < 0:
raise ValueError("Age cannot be negative")
self._age = value이제 자동 validation을 사용하여 age를 설정할 수 있습니다:
person = Person("Alice", 30)
person.age = 31 # 유효성 검사와 함께 setter를 사용합니다
print(person.age) # getter를 사용합니다
# 이렇게 하면 오류가 발생합니다:
# person.age = -5 # ValueError: 나이는 음수일 수 없습니다출력:
31값을 계산하는 computed properties를 Create하세요:
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
@property
def area(self):
return self.width * self.height
rect = Rectangle(5, 3)
print(rect.area) # 5 * 3 = 15를 계산합니다출력:
15핵심 사항: Property 데코레이터를 사용하면 메서드가 attribute처럼 보입니다. getter에는 @property를, setter에는 @attribute_name.setter를 사용하세요. 이렇게 하면 간단한 attribute 접근 구문을 유지하면서 data validation과 계산된 values를 사용할 수 있습니다.
챌린지
중급temperature.py에서 Celsius와 Fahrenheit 사이를 변환하는 Temperature class를 완성하세요. 그런 다음 driver.py에서 이 class를 사용하여 temperature 변환을 테스트하세요. 단계별 지침은 두 파일의 TODO 주석을 따르세요.
각 변환을 [celsius]°C is [fahrenheit]°F 형식으로 출력하되, Celsius 값은 주어진 그대로 출력하고 Fahrenheit 값은 Python이 계산한 값으로 출력하세요. 숫자를 반올림하거나 형식을 지정하지 마세요. driver가 출력하는 두 줄은 다음과 같습니다.
25°C is 77.0°F
37.0°C is 98.6°F직접 해보기
# TODO: temperature 모듈에서 Temperature 클래스를 임포트하세요
# 클래스를 테스트하세요:
# TODO: 25°C에서 temperature 인스턴스를 생성하세요
temp = None # 실제 Temperature 인스턴스로 교체하세요
# TODO: 섭씨와 화씨 값을 모두 출력하세요
# TODO: 다음 형식을 사용하세요: "25.0°C is 77.0°F"
# TODO: 온도를 98.6°F로 설정하세요
# TODO: 변환이 작동하는지 확인하기 위해 두 값을 다시 출력하세요
# TODO: 이전과 동일한 형식을 사용하세요이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
객체 지향 프로그래밍의 모든 레슨
직접 연습해 보세요: 온라인 Python 컴파일러