Python 객체 지향 프로그래밍의 매직 메소드 이해

객체 지향 프로그래밍의 매직 메소드

매직 메소드는 클래스 내에서 특정 조건이 충족될 때 자동으로 호출되는 더블 언더스코어 메소드를 의미합니다.

클래스에서 사용되는 주요 매직 메소드

더블 언더 메소드 자동 호출 조건
__init__ 객체가 생성되고 초기화될 때 호출
__str__ 객체가 출력될 때 호출
__call__ 객체가 함수처럼 호출될 때
__getattr__ 존재하지 않는 속성에 접근할 때 호출
__getattribute__ 모든 속성에 접근할 때 호출 (잘 사용되지 않음)
__setattr__ 속성을 설정하거나 수정할 때 호출
__enter__ with 문을 사용할 때 시작 시점에 호출
__exit__ with 문이 끝날 때 호출
  1. __init__
class Sample:
    def __init__(self, x, y):
        self.x = x
        self.y = y

instance = Sample(33, 44)
print(instance.__dict__)

이 메소드는 클래스 인스턴스가 생성될 때 호출됩니다. 2. __str__

class AnotherSample:
    def __str__(self):
        return 'AnotherSample 클래스의 문자열 표현'
    
instance = AnotherSample()
print(instance)  # AnotherSample 클래스의 문자열 표현

이 메소드는 반드시 문자열 값을 반환해야 합니다. 3. __call__

class CallableClass:
    value = 556677
    def __call__(self, *args, **kwargs):
        print(self)
        print(args, kwargs)
        return self.value
    
obj = CallableClass()
print(obj(33, 44, name='test'))
"""
<__main__.CallableClass object at 0x...>
(33, 44) {'name': 'test'}
556677
"""

이 메소드는 객체를 함수처럼 호출할 수 있게 해줍니다. 4. __getattr__

class MissingAttr:
    attr = 556677
    def __getattr__(self, item):
        return f'{item} 속성이 없습니다.'

instance = MissingAttr()
print(instance.attr)  # 556677
print(instance.nonexistent_attr)  # nonexistent_attr 속성이 없습니다.
  1. __getattribute__
class AttributeAccess:
    attr = 556677

    def __getattribute__(self, item):
        return '접근 제어자'

instance = AttributeAccess()
print(instance.attr)  # 접근 제어자
print(instance.nonexistent_attr)  # 접근 제어자
  1. __setattr__
class SetAttribute:
    history = []

    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __setattr__(self, key, value):
        self.history.append(f'키 {key}: 값 {value} 추가')

obj1 = SetAttribute('tester', 20)
obj2 = SetAttribute('example', 21)
print(SetAttribute.history)
"""
['키 name: 값 tester 추가', '키 age: 값 20 추가',
'키 name: 값 example 추가', '키 age: 값 21 추가']
"""
  1. __enter____exit__
class ContextManager:
    def action(self):
        print('작업 수행 중')

    def __enter__(self):
        print('컨텍스트 시작')
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        print('컨텍스트 종료')

with ContextManager() as cm:
    cm.action()
"""
컨텍스트 시작
작업 수행 중
컨텍스트 종료
"""

사용자 정의 딕셔너리 타입 예제:

class CustomDict(dict):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)

    def __setattr__(self, key, value):
        self[key] = value

    def __getattr__(self, item):
        return self[item]

data = {'first_name': 'tester', 'age': '20'}
custom_dict = CustomDict(**data)
print(custom_dict.first_name)
custom_dict.first_name = 'new_tester'
print(custom_dict.first_name)

추가적인 매직 메소드들

더블 언더 메소드 자동 호출 조건
__repr__ 대화형 환경에서 객체를 출력할 때
__del__ 객체가 메모리에서 삭제될 때 호출
__format__ 객체를 형식화하여 출력할 때
__getitem__, __setitem__, __delitem__ 객체를 딕셔너리처럼 다룰 때 호출
__doc__ 클래스 설명 정보
__iter__, __next__ 객체를 반복 가능하게 만들 때
__len__ 객체의 길이를 반환할 때
__hash__ 객체를 해시 가능하게 만들 때
__eq__ 객체 간 비교 연산을 정의할 때

태그: python 객체지향프로그래밍 매직메소드

6월 1일 07:28에 게시됨