@property 데코레이터
getter, setter 및 deleter에 property를 사용합니다.
@property 데코레이터은(는) CoddyKit의 무료 Python Academy 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Python Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Python Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
소개
@property를 사용하는 이유
class Circle:
def __init__(self, r): self._r = r
@property
def radius(self): return self._r
c = Circle(5)
print(c.radius) # no ()계산된 속성
import math
class Circle:
def __init__(self, r): self._r = r
@property
def area(self): return math.pi * self._r**2
c = Circle(5)
print(round(c.area, 2))속성 설정자
class Circle:
def __init__(self, r): self._r = r
@property
def radius(self): return self._r
@radius.setter
def radius(self, val):
if val <= 0: raise ValueError('radius must be positive')
self._r = val
c = Circle(5)
c.radius = 10
print(c.radius)속성 삭제자
class User:
def __init__(self, name): self._name = name
@property
def name(self): return self._name
@name.deleter
def name(self): del self._name
u = User('Alice')
del u.name
print(hasattr(u, '_name'))읽기 전용 속성
class Const:
def __init__(self, v): self._v = v
@property
def value(self): return self._v
c = Const(42)
print(c.value)
try: c.value = 99
except AttributeError as e: print(e)유효성 검사가 있는 속성
class BoundedInt:
def __init__(self, lo, hi): self.lo,self.hi=lo,hi; self._v=lo
@property
def value(self): return self._v
@value.setter
def value(self, v):
if not self.lo <= v <= self.hi:
raise ValueError(f'{v} out of [{self.lo},{self.hi}]')
self._v = v
b = BoundedInt(0, 10)
b.value = 5
print(b.value)property를 사용한 캐싱
class Expensive:
_cache = None
@property
def result(self):
if self._cache is None:
self._cache = sum(range(1000))
return self._cache
e = Expensive()
print(e.result)
print(e.result)cached_property (파이썬 3.8 이상)
from functools import cached_property
import math
class Circle:
def __init__(self, r): self.r = r
@cached_property
def area(self): return math.pi * self.r**2
c = Circle(5)
print(round(c.area, 2))Property와 __slots__ 비교
class Point:
__slots__ = ('_x', '_y')
def __init__(self, x, y): self._x,self._y=x,y
@property
def x(self): return self._x
p = Point(1, 2)
print(p.x)@property를 사용할 시점
# Before: class Person:
# def __init__(self, age): self.age = age
# After: add validation without changing caller code
class Person:
def __init__(self, age): self.age = age
@property
def age(self): return self._age
@age.setter
def age(self, v):
if v < 0: raise ValueError('negative age')
self._age = v
p = Person(30)
print(p.age)빠른 확인
복습
계속하기
자주 묻는 질문
“@property 데코레이터” 강의는 무료인가요?
네 — “@property 데코레이터” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Python Academy 강의 전체를 잠금 해제할 수 있습니다. Python Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
“@property 데코레이터”에서 뭘 배우나요?
getter, setter 및 deleter에 property를 사용합니다. 브라우저에서 직접 실행하는 실습 코드로 Python Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Python Academy을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Python Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.
“@property 데코레이터” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Python Academy 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Python Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 일급 객체로서의 함수
- 사용자 정의 데코레이터 작성
- @property 데코레이터
- @classmethod와 @staticmethod