내장 데코레이터 (Built-in Decorators)

파이썬에는 다양한 내장 데코레이터가 있으며, 이들은 코드를 최적화하고 기능을 확장하는 데 중요한 역할을 한다.

@property

@property는 메서드를 속성처럼 사용할 수 있게 해주는 데코레이터.
getter, setter, deleter 기능을 제공하여 데이터의 캡슐화와 접근 제어를 가능하게 한다.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Person:
    def __init__(self):
        self._age = 0

    @property
    def age(self):
        """getter 메서드"""
        return self._age

    @age.setter
    def age(self, value):
        """setter 메서드"""
        if value < 0:
            raise ValueError("나이는 음수일 수 없습니다")
        self._age = value

    @age.deleter
    def age(self):
        """deleter 메서드"""
        print("나이 정보가 삭제되었습니다")
        del self._age

# 사용 예시
person = Person()
person.age = 25  # setter 호출
print(person.age)  # getter 호출
del person.age  # deleter 호출

@abstractmethod

추상 메서드를 정의하는 데코레이터.
abc(Abstract Base Classes) 모듈과 함께 사용되며, 하위 클래스에서 반드시 구현해야 하는 메서드를 지정할 때 사용.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
from abc import ABC, abstractmethod

class Shape(ABC):
    @abstractmethod
    def area(self):
        """도형의 넓이를 계산하는 추상 메서드"""
        pass

    @abstractmethod
    def perimeter(self):
        """도형의 둘레를 계산하는 추상 메서드"""
        pass

class Rectangle(Shape):
    def __init__(self, width, height):
        self.width = width
        self.height = height

    def area(self):
        return self.width * self.height

    def perimeter(self):
        return 2 * (self.width + self.height)

@cached_property (Python 3.8+)

@property의 확장된 버전으로, 계산 결과를 캐시하여 재사용한다.
계산 비용이 큰 속성에 유용하다.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
from functools import cached_property

class DataAnalyzer:
    def __init__(self, data):
        self.data = data

    @cached_property
    def complex_calculation(self):
        """시간이 오래 걸리는 계산을 수행하고 결과를 캐시"""
        print("복잡한 계산 수행 중…")
        result = sum(x * x for x in self.data)
        return result

# 사용 예시
analyzer = DataAnalyzer(range(1000000))
print(analyzer.complex_calculation)  # 첫 번째 호출: 계산 수행
print(analyzer.complex_calculation)  # 두 번째 호출: 캐시된 결과 사용

@total_ordering

클래스에 비교 메서드들을 자동으로 생성해주는 데코레이터.
__eq__와 다른 하나의 비교 메서드만 구현하면 나머지 비교 메서드들을 자동으로 생성한다.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
from functools import total_ordering

@total_ordering
class Number:
    def __init__(self, value):
        self.value = value

    def __eq__(self, other):
        return self.value == other.value

    def __lt__(self, other):
        return self.value < other.value

# 자동으로 __le__, __gt__, __ge__ 메서드가 생성됨
n1 = Number(5)
n2 = Number(10)
print(n1 < n2)   # True
print(n1 <= n2)  # True
print(n1 > n2)   # False
print(n1 >= n2)  # False

참고 및 출처