decorater는 다른 함수를 인자로 받아 해당 함수의 동작을 확장하고 확장된 동작으로 새 함수를 반환하는 함수이다. 가독성 및 효율성 증대가 가능하며 메서드 위에 @decorater 형식으로 데코레이터를 추가할 수 있다.
# decorater 사용 전
def stand():
print('stand 함수 실행')
print('stand')
def sit():
print('sit 함수 실행')
print('sit')
# decorater 사용 후
def trace(func):
def wrapper():
print(func.__name__, '함수 실행')
func()
return wrapper
@trace
def stand():
print('stand')
@trace
def sit():
print('sit')
클래스의 속성값에 직접적인 접근을 막고, 은닉하기 위해 사용한다. 추가 기능을 삽입하여 직접적인 접근 제한할 수 있고, 속성 이름 앞에 더블언더바(더던)을 붙여 맹글링을 통해 은닉할 수 있다. 맹글링이란 속성의 이름을 바꿔버려 접근하지 못하도록 하는 것이다. 이를 통해 변수를 private화 한다. 하지만, dir 함수를 통해 ‘_클래스이름__속성이름’으로 변경된 것임을 확인할 수 있다. 이는 은닉이 완전하지 못하며, 대신 오버라이딩을 막을 수 있는 기능이 가능하다는 것을 보여준다.
class Example:
def __init__(self):
self.__count = 1
@property
def count(self): # getter
return self.__count
@count.setter
def count(self, value): # setter
if 0 < value < 10: # 추가 기능 삽입
self.__count = value
else:
print("error")
self.__count = 1
if __name__ == '__main__':
ex = Example()
print(ex.count)
클래스 또는 클래스로부터 만들어진 인스턴스에 의존하지 않는 정적인 메서드를 정의하는데 사용한다. 보통의 클래스 내부 메서드는 첫 번째 인자로 self를 받지만, staticmethod는 self를 인자로 받지 않고 일반 메서드와 동일하게 입력받는다. 클래스 내부 메서드 위에 @staticmethod를 추가하여 정의한다.
class Example:
sum = 0
@staticmethod
def staticmethod_ex(a, b):
return a + b + Example.sum
result = Example.staticmethod_ex(1 , 2) # result = 3
클래스 자체를 첫 번째 인자로 입력받아 클래스 변수에 접근하여 수정 가능하게 하는데 사용한다. 클래스 내부 메서드 위에 @classmethod를 추가하여 정의한다.
class Example:
sum = 0
@classmethod
def classmethod_ex(cls, a):
cls.sum += a
Example.classmethod_ex(1) # Example.sum = 1
서로 다른 인수 유형 및 반환 유형에 따라 처리 방법을 다르게 하는 것을 가능하게 하는 데코레이터이다. typing 모듈과 함께 사용되며 보다 구체적인 유형 검사와 향상된 가독성을 가능하게 한다. 메서드 위에 @overload를 추가하여 정의한다.
from typing import List, Tuple, Union, overload
@overload
def my_func(x: int, y: int) -> int:
pass
@overload
def my_func(x: str, y: str) -> str:
pass
@overload
def my_func(x: List[int], y: List[int]) -> Tuple[int, int]:
pass
def my_func(x, y):
# Implementation of the function for each specific overload
if isinstance(x, int) and isinstance(y, int):
return x + y
elif isinstance(x, str) and isinstance(y, str):
return x + y
elif isinstance(x, list) and isinstance(y, list):
return len(x), len(y)
else:
raise TypeError("Invalid argument types")
처음 세 개의 my_func 함수는 각각 다른 인수 및 반환 유형을 가지고 있음을 나타낸다. 이는 네 번째 my_func에서 유형 힌트 역할을 한다.