파이썬에서 기본 dict 자료형을 확장하면서도 특정한 제한을 두고 싶을 때, dict를 상속받아 사용자 정의 클래스를 만드는 것이 일반적입니다. 예를 들어, 딕셔너리에 새로운 키의 추가를 제한하거나, 특정 키만 수정할 수 있도록 제한할 수 있습니다.

아래에서는 딕셔너리의 확장을 제한하는 다양한 방법과 그에 해당하는 코드 샘플을 소개하겠습니다.

읽기 전용 딕셔너리 (ReadOnlyDict)

이 예제에서는 딕셔너리를 읽기 전용으로 만들어, 어떤 수정도 불가능하게 합니다.

코드 설명

  • __setitem__, __delitem__, clear, pop, popitem, setdefault, update: 모든 수정 메서드를 오버라이드하여 예외를 발생시킵니다.

코드 샘플

class ReadOnlyDict(dict):
    def __readonly__(self, *args, **kwargs):
        raise TypeError("This dictionary is read-only")

    __setitem__ = __readonly__
    __delitem__ = __readonly__
    clear = __readonly__
    pop = __readonly__
    popitem = __readonly__
    setdefault = __readonly__
    update = __readonly__

# 사용 예제
try:
    readonly_dict = ReadOnlyDict(a=1, b=2)
    print(readonly_dict)  # 출력: {'a': 1, 'b': 2}

    # 값 수정 시도
    readonly_dict['a'] = 10  # TypeError 발생
except TypeError as e:
    print(e)  # 출력: This dictionary is read-only

try:
    # 키 삭제 시도
    del readonly_dict['a']  # TypeError 발생
except TypeError as e:
    print(e)  # 출력: This dictionary is read-only

try:
    # update 메서드 사용 시도
    readonly_dict.update({'c': 3})  # TypeError 발생
except TypeError as e:
    print(e)  # 출력: This dictionary is read-only

출력 결과

{'a': 1, 'b': 2}
This dictionary is read-only
This dictionary is read-only
This dictionary is read-only

결론

파이썬의 dict 자료형을 상속받아 사용자 정의 클래스를 만드는 것은 매우 유용하며, 다양한 방식으로 딕셔너리의 동작을 확장하거나 제한할 수 있습니다. 위의 예제들을 통해 다음과 같은 기능을 구현할 수 있습니다:

  1. 고정 키 집합: 특정 키만 수정 가능하게 하고, 새로운 키의 추가를 제한.
  2. 읽기 전용 딕셔너리: 딕셔너리를 수정 불가능하게 만들어 데이터의 무결성을 유지.
  3. 최대 크기 제한: 딕셔너리에 추가할 수 있는 항목의 수를 제한.
  4. 타입 제한: 키와 값의 타입을 제한하여 데이터의 일관성을 유지.

이러한 사용자 정의 딕셔너리를 활용하면, 애플리케이션의 요구사항에 맞게 데이터 구조를 더욱 정교하게 제어할 수 있습니다.

+ Recent posts