"일꾼이 일을 잘하려면 먼저 도구를 갈고 닦아야 한다." - 공자, 『논어』.
첫 장 > 프로그램 작성 > Python의 마법 방법 배우기: 간단한 설명

Python의 마법 방법 배우기: 간단한 설명

2024-08-18에 게시됨
검색:523

Learn Python Magic Methods: A Simple Explanation

Python의 매직 메소드 이해

dunder 메소드라고도 알려진 Python의 매직 메소드(이름의 시작과 끝에 이중 밑줄이 있기 때문에)를 사용하면 다양한 작업에 대한 객체의 동작을 정의할 수 있습니다. 이는 사용자 정의 동작을 활성화하고 클래스가 내장 유형처럼 작동하도록 할 수 있습니다. 이 블로그에서는 매직 메소드의 다양한 카테고리를 살펴보고 자세한 설명을 제공하며 실제 예제와 사용 사례를 제공합니다.

1. 속성 액세스 방법

이 매직 메소드는 객체의 속성이 액세스, 수정 또는 삭제되는 방법을 제어합니다.

__getattr__ 및 __getattribute__

  • __getattr__: 객체에서 속성을 찾을 수 없을 때 호출됩니다.

  • __getattribute__: 모든 속성에 액세스하기 위해 무조건 호출됩니다.

예: 로깅을 통한 맞춤 속성 액세스

class LoggedAttributes:
    def __init__(self, name):
        self.name = name

    def __getattr__(self, item):
        print(f"Accessing non-existent attribute: {item}")
        return None

    def __getattribute__(self, item):
        print(f"Getting attribute: {item}")
        return super().__getattribute__(item)

# Usage
obj = LoggedAttributes("Alice")
print(obj.name)  # Output: Getting attribute: name\nAlice
print(obj.age)   # Output: Accessing non-existent attribute: age\nNone

실용 사례: 디버깅 시나리오에서 속성 액세스를 로깅하여 속성에 액세스하거나 수정하는 시기와 방법을 추적합니다.

__setattr__ 및 __delattr__

  • __setattr__: 속성 할당을 시도할 때 호출됩니다.

  • __delattr__: 속성 삭제를 시도할 때 호출됩니다.

예: 검증을 통한 사용자 정의 속성 수정

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

    def __setattr__(self, key, value):
        if key == "age" and value 



실용 사례: 속성을 설정하거나 삭제할 때 유효성 검사 규칙 또는 제한을 적용합니다.

2. 컨테이너 메소드

이러한 마법 메서드를 사용하면 개체가 컨테이너(목록, 사전 등)처럼 동작할 수 있습니다.

__len__, __getitem__, __setitem__, __delitem__ 및 __iter__

  • __len__: 컨테이너의 길이를 반환합니다.

  • __getitem__: 주어진 인덱스나 키에서 항목을 검색합니다.

  • __setitem__: 주어진 인덱스나 키에 항목을 설정합니다.

  • __delitem__: 지정된 인덱스나 키에서 항목을 삭제합니다.

  • __iter__: 반복자 객체를 반환합니다.

예: 사용자 정의 목록형 객체

class CustomList:
    def __init__(self):
        self._items = []

    def __len__(self):
        return len(self._items)

    def __getitem__(self, index):
        return self._items[index]

    def __setitem__(self, index, value):
        self._items[index] = value

    def __delitem__(self, index):
        del self._items[index]

    def __iter__(self):
        return iter(self._items)

    def append(self, item):
        self._items.append(item)

# Usage
cl = CustomList()
cl.append(1)
cl.append(2)
cl.append(3)
print(len(cl))  # Output: 3
print(cl[1])    # Output: 2
for item in cl:
    print(item)  # Output: 1 2 3

실용 사례: 표준 목록 작업을 지원하면서 특수한 동작이나 추가 메서드가 필요한 사용자 정의 컬렉션 클래스를 만듭니다.

3. 수치 및 비교 방법

이러한 메서드는 클래스의 개체가 숫자 연산 및 비교와 상호 작용하는 방식을 정의합니다.

수치법

  • __add__, __sub__, __mul__, __truediv__, __floordiv__, __mod__, __pow__: 산술 연산을 정의합니다.

예: 사용자 정의 복소수 클래스

class Complex:
    def __init__(self, real, imag):
        self.real = real
        self.imag = imag

    def __add__(self, other):
        return Complex(self.real   other.real, self.imag   other.imag)

    def __sub__(self, other):
        return Complex(self.real - other.real, self.imag - other.imag)

    def __repr__(self):
        return f"({self.real}   {self.imag}i)"

# Usage
c1 = Complex(1, 2)
c2 = Complex(3, 4)
print(c1   c2)  # Output: (4   6i)
print(c1 - c2)  # Output: (-2   -2i)

실용 사례: 복소수, 벡터 또는 행렬과 같은 사용자 정의 숫자 유형을 구현합니다.

비교 방법

  • __eq__, __ne__, __lt__, __le__, __gt__, __ge__: 비교 연산을 정의합니다.

예: 사용자 정의 클래스에 대한 전체 순서 구현

from functools import total_ordering

@total_ordering
class Book:
    def __init__(self, title, author):
        self.title = title
        self.author = author

    def __eq__(self, other):
        return (self.title, self.author) == (other.title, other.author)

    def __lt__(self, other):
        return (self.title, self.author) 



실용 사례: 사용자 정의 개체를 정렬하거나 비교할 수 있도록 하며, 힙, 이진 검색 트리와 같은 데이터 구조에서 유용하거나 단순히 사용자 정의 개체 목록을 정렬할 때 유용합니다.

4. 컨테이너 메서드: 실제 사용 사례

대소문자를 구분하지 않는 키를 사용한 사용자 정의 사전

키를 대소문자를 구분하지 않고 처리하는 사전과 같은 객체를 생성합니다.

예: 대소문자를 구분하지 않는 사전

class CaseInsensitiveDict:
    def __init__(self):
        self._data = {}

    def __getitem__(self, key):
        return self._data[key.lower()]

    def __setitem__(self, key, value):
        self._data[key.lower()] = value

    def __delitem__(self, key):
        del self._data[key.lower()]

    def __contains__(self, key):
        return key.lower() in self._data

    def keys(self):
        return self._data.keys()

    def items(self):
        return self._data.items()

    def values(self):
        return self._data.values()

# Usage
cid = CaseInsensitiveDict()
cid["Name"] = "Alice"
print(cid["name"])  # Output: Alice
print("NAME" in cid)  # Output: True

실용 사례: 키가 대소문자를 구분하지 않고 처리되어야 하는 사전을 생성하며 사용자 입력, 구성 설정 등을 처리하는 데 유용합니다.

결론

매직 메서드는 Python에서 개체의 동작을 사용자 정의하는 강력한 방법을 제공합니다. 이러한 메서드를 이해하고 효과적으로 사용하면 클래스가 더욱 직관적으로 만들어지고 Python의 내장 함수 및 연산자와 원활하게 통합될 수 있습니다. 사용자 정의 숫자 유형, 컨테이너 또는 속성 액세스 패턴을 구현하든 매직 메소드는 코드의 유연성과 기능을 크게 향상시킬 수 있습니다.

릴리스 선언문 이 글은 https://dev.to/tapstechie/learn-python-magic-methods-a-simple-explanation-21ap?1 에서 복제되었습니다. 침해 내용이 있는 경우, [email protected]으로 연락하여 삭제하시기 바랍니다.
최신 튜토리얼 더>

부인 성명: 제공된 모든 리소스는 부분적으로 인터넷에서 가져온 것입니다. 귀하의 저작권이나 기타 권리 및 이익이 침해된 경우 자세한 이유를 설명하고 저작권 또는 권리 및 이익에 대한 증거를 제공한 후 이메일([email protected])로 보내주십시오. 최대한 빨리 처리해 드리겠습니다.

Copyright© 2022 湘ICP备2022001581号-3