본문 바로가기

Python

파이썬 중급 (Inflearn Original) 5편 - Special Method(Magic Method) - (__add__, __ge__, __le__, __sub__)


코드 내용

#Chapter03-01
# Special Method(Magic Method)
# 파이썬의 핵심 -> 시퀀스(Sequence), 반복(Iterator), 함수(Function), Class(클래스)
# 클래스 안에 정의할 수 있는 특별한(Built-in) 메서드 

# 기본형

print(int)
print(float)

# 모든 속성 및 메소드 출력

print(dir(int))
print(dir(float))

n = 10

print(n+100)                    # '+' 연산자는 무엇일까?

print(n.__add__(100))           # Int.__add__()를 호출해주는 특이한 연산자

print(n.__bool__(), bool(n))    # n이 0이 아닌 경우 True를 반환하는 함수

print(n*100, n.__mul__(100))    # '+'와 마찬가지로 '*' 또한 Int.__mul__()를 호출해주는 특이한 연산자

print()
print()



#클래스 예제1
class Fruit:
    def __init__(self, name, price):
        self._name = name
        self._price = price

    def __str__(self):
        return 'Fruit Class info: {}, {}'.format(self._name, self._price)
    
    def __add__(self, other):               # 우리가 직접 '+' 연산자에 의해 호출될 함수 __add__를 작성
        print('Called __add__')
        return self._price + other._price

    def __sub__(self, other):
        print('Called __sub__')
        return self._price - other._price   # '-' 연산자에 의해 호출

    def __le__(self, other):                # '<=' 연산자에 의해 호출
        print('Called __le__')
        if self._price <= other._price:
            return True
        else:
            return False

    def __ge__(self, other):                # '>=' 연산자에 의해 호출
        print('Called __ge__')
        if self._price >= other._price:
            return True
        else:
            return False

# create instance
s1 = Fruit('Orange',7500)
s2 = Fruit('Banana', 3000)

# normal calculate
print(s1._price + s2._price)
print(s1._price - s2._price)

# special method (magic method)
print(s1 + s2)
print(s1-s2)
print(s1 >= s2)
print(s1 <= s2)

실행 결과

PS C:\Users\82107\Desktop\파이썬중급강의>  ${env:DEBUGPY_LAUNCHER_PORT}='65245'; & 'C:\Users\82107\Anaconda3\python.exe' 'c:\Users\82107\.vscode\extensions\ms-python.python-2020.4.76186\pythonFiles\lib\python\debugpy\wheels\debugpy\launcher' 'c:\Users\82107\Desktop\파이썬중급강
의\p_study\chapter03_01.py' 
<class 'int'>
<class '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__', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']
['__abs__', '__add__', '__bool__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__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__', '__set_format__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', 'as_integer_ratio', 'conjugate', 'fromhex', 'hex', 'imag', 'is_integer', 'real']
110
110
True True
1000 1000


10500
4500
Called __add__
10500
Called __sub__
4500
Called __ge__
True
Called __le__
False