본문 바로가기

Python/Intermediate

[Python] Magic Method(1)

워밍업

 

# 참조 : https://docs.python.org/3/reference/datamodel.html#special-method-names
# 클래스 안에서 정의할 수 있는 특별한(built-in) 매소드, 파이썬에 이미 정의된 함수들임.

# 기본형 - 모두 클래스입니다.
print(int)
print(float)
# <class 'int'>
# <class 'float'>

# 모든 속성 및 메소드 출력
print(dir(int))
print(dir(float))
# ['__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__', 'as_integer_ratio', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']
# ['__abs__', '__add__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getformat__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__int__', '__le__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__pos__', '__pow__', '__radd__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rmod__', '__rmul__', '__round__', '__rpow__', '__rsub__', '__rtruediv__', '__setattr__', '__setformat__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', 'as_integer_ratio', 'conjugate', 'fromhex', 'hex', 'imag', 'is_integer', 'real']


n = 10

# int 클래스에 __add__ 함수가 이미 정의되어 있어서 더하기 메소드가 실행된다.
# '+' 대신에 __add__() 함수를 직접 호출해도 된다.
print(n + 100)
print(n.__add__(100))
# 110
# 110

print(n.__bool__(), bool(n))
print(n * 100, n.__mul__(100))
# True True
# 1000 1000

 

 

클래스 예제

 

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

    def __str__(self):
        return '(str)Fruit Class Info : {} , {}'.format(self._name, self._price)

    def __ge__(self, x):
        print('Called >> __ge__ Method.')
        if self._price >= x._price:
            return True
        else:
            return False

    def __le__(self, x):
        print('Called >> __le__ Method.')
        if self._price <= x._price:
            return True
        else:
            return False

    def __sub__(self, x):
        print('Called >> __sub__ Method.')
        return self._price - x._price

    def __add__(self, x):
        print('Called >> __add__ Method.')
        return self._price + x._price

 

Magic 매소드 샘플

 

# 인스턴스 생성
s1 = Fruit('Orange', 7500)
s2 = Fruit('Banana', 3000)

# 매직메소드 출력
print(s1 >= s2)
print(s1 <= s2)
print(s1 - s2)
print(s2 - s1)
print(s1 + s2)
print(s1)
print(s2)

--------------------------------------------[result]

Called >> __ge__ Method.
True
Called >> __le__ Method.
False
Called >> __sub__ Method.
4500
Called >> __sub__ Method.
-4500
Called >> __add__ Method.
10500
(str)Fruit Class Info : Orange , 7500
(str)Fruit Class Info : Banana , 3000

'Python > Intermediate' 카테고리의 다른 글