>  기사  >  백엔드 개발  >  Python의 마법 방법 배우기: 간단한 설명

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

PHPz
PHPz원래의
2024-08-09 06:44:42535검색

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 < 0:
            raise ValueError("Age cannot be negative")
        super().__setattr__(key, value)

    def __delattr__(self, item):
        if item == "name":
            raise AttributeError("Can't delete attribute 'name'")
        super().__delattr__(item)

# Usage
p = Person("Alice", 30)
p.age = 25  # Works fine
# p.age = -1  # Raises ValueError
# del p.name  # Raises AttributeError

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

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) < (other.title, other.author)

    def __repr__(self):
        return f"{self.title} by {self.author}"

# Usage
book1 = Book("Title1", "Author1")
book2 = Book("Title2", "Author2")
books = [book2, book1]
print(sorted(books))  # Output: [Title1 by Author1, Title2 by Author2]

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

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의 내장 함수 및 연산자와 원활하게 통합될 수 있습니다. 사용자 정의 숫자 유형, 컨테이너 또는 속성 액세스 패턴을 구현하든 매직 메소드는 코드의 유연성과 기능을 크게 향상시킬 수 있습니다

위 내용은 Python의 마법 방법 배우기: 간단한 설명의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.