본문 바로가기

Python

파이썬 중급 (Inflearn Original) 6편 - Special Method(Magic Method) - (__add__, __mul__, __bool__, __repr__)


코드 내용

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

# 클래스 예제2
# (5,2) + (4,3) = (9,5)
# (10,3) * 5 = (50,15)
# Max((5,10)) = 10


class Vector(object): # object를 상속
    '''
    ^^*
    '''
    
    def __init__(self, *args):
        """
        Create a vector, example : v = Vector(5,10)
        """
        if len(args) == 0: # e.g. Vector()
            self._x, self._y = 0, 0
        else:
            self._x , self._y = args
    
    def __repr__(self):                                 # 개발자 입장에서 객체의 정보를 return 해주는 함수
        ''' Return the vector informations'''
        return 'Vector(%r, %r)' % (self._x, self._y) 


    def __str__(self):                                  # 사용자 입장에서 객체의 정보를 return 해주는 함수
        return '({},{})'.format(self._x, self._y)

    def __add__(self,other):                                        # '+' 연산에 대한 함수
        ''' Return the vector addition of   self and other'''
        return Vector(self._x + other._x, self._y + other._y)

    def __mul__(self,other):                                        # '*' 연산에 대한 함수
        if type(other) == int:
            return Vector(self._x * other , self._y * other)
        elif type(other) == Vector:
            return Vector(self._x * other._x, self._y * other._y)

    def __bool__(self):                                             # 객체의 True/False를 return 해주는 함수
        return bool(max(self._x,self._y))


# Create Vector instance 

v1 = Vector(5,7)
v2 = Vector(23,35)
v3 = Vector(-15,200)
v4 = Vector()
v5 = Vector(-1,0)


print(v1,v2,v3,v4,v5)

print(v1 + v2)
print(v2 * 10 )
print(v2 * v1)
print(bool(v1), bool(v2), bool(v5))

if bool(v4):
    print('ok')

실행 결과

Windows PowerShell
Copyright (C) Microsoft Corporation. All rights reserved.

새로운 크로스 플랫폼 PowerShell 사용 https://aka.ms/pscore6

PS C:\Users\82107\Desktop\파이썬중급강의\p_study>  & 'C:\Users\82107\AppData\Local\Programs\Python\Python37\python.exe' 'c:\Users\82107\.vscode\extensions\ms-python.python-2020.5.80290\pythonFiles\lib\python\debugpy\wheels\debugpy\launcher' '55059' '--' 'c:\Users\82107\Desktop\파이썬중급강의\p_study\chapter03_02.py'
(5,7) (23,35) (-15,200) (0,0) (-1,0)
(28,42)
(230,350)
(115,245)
True True False
PS C:\Users\82107\Desktop\파이썬중급강의\p_study>