반응형

1. 매직 메서드(special mehod)

클래스 안에 정의할 수 있는 특별한 메서드로 파이썬 내에 이미 만들어져 있는 메서드입니다. 공식문서에서는 special method라 표현하는데 magic method 라는 단어와 혼용해서 사용되고 있는 Built-in 함수입니다.

print(int)
>>> <class 'int'>
print(dir(int))
>>> ['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']

n = 10

print(n + 100)
>>> 110
print(n.__add__(100))
>>> 110

int는 가장 흔하게 사용하는 데이터 타입인데, 이 int 자체도 클래스이며 여러 메서드를 갖고 있습니다. dir()을 통해 어떤 동작이 가능한지 내장된 매직 메서드를 확인할 수 있습니다.

2. magic method 사용예시

class Icecream():
    def __init__(self, name, price) :
        self._name = name
        self._price = price

    def __str__(self) : 
        return 'Icecream Class info : {}, {}'.format(self._name, self._price)

    def __add__(self, x) :
        return self._price + x._price
        #return self._price + x._price * 2


ice1 = Icecream('choco', 2000)
ice2 = Icecream('rainbow', 3000)

print(ice1._price + ice2._price)
>>> 5000
print(ice1 + ice2)
>>> 5000

아이스크림의 이름과 가격을 갖는 객체를 만드는 클래스를 구현했습니다.
만약 두 아이스크림의 가격을 더하고 싶다면 일반적으로 print(ice1._price + ice2._price) 로 각 객체의 인스턴스 변수를 가져와야 하기 때문에 코드가 길어지고 반복작업이 요구되지만 내부에 add 매직 메서드를 구현함으로 간단하게 클래스간 연산이 가능하도록 할 수 있습니다.
이렇게 매직 메서드를 사용하며 가져갈 수 있는 가장 큰 이점은 본연의 기능에 우리가 원하는 추가적인 작업을 넣어 함께 실행할 수 있다는 점입니다.

 

 

 

해당 게시물은 우리를 위한 프로그래밍 : 파이썬 중급 (Inflearn Original)을 참고합니다.

반응형
복사했습니다!