본문 바로가기

Python/Intermediate

[Python] Magic Method(2)

클래스 샘플2

 

class Vector(object):
    def __init__(self, *args):
        # function Doctring
        '''(init)Create a vector, example : v = Vector(5,10)'''
        if len(args) == 0:
            self._x, self._y = 0, 0
        else:
            self._x, self._y = args # un-packing

    def __repr__(self):
        '''(repr)Returns the vector infomations'''
        return '(repr)Vector(%r, %r)' % (self._x, self._y)

    def __add__(self, other):
        '''(add)Returns the vector addition of self and other'''
        return Vector(self._x + other._x, self._y + other._y)
    
    def __mul__(self, y):
        return Vector(self._x * y, self._y * y)

    def __bool__(self):
        return bool(max(abs(self._x), abs(self._y)))

    def __max__(self, other): # 임의로 만들 매소드, 매직 매소드 아님
        '''__max__'''
        return Vector(max(self._x, other._x), max(self._y, other._y))

# Vector 인스턴스 생성
v1 = Vector(5,7)
v2 = Vector(23, 35)
v3 = Vector()

# 매직메소드 출력
print(Vector.__init__.__doc__)
print(Vector.__repr__.__doc__)
print(Vector.__add__.__doc__)
print(v1, v2, v3)
print(v1 + v2)
print(v1 * 3)
print(v2 * 10)
print(bool(v1), bool(v2))
print(bool(v3))
print('Vector(-1, 0): ', bool(Vector(-1, 0)))

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

(init)Create a vector, example : v = Vector(5,10)
(repr)Returns the vector infomations
(add)Returns the vector addition of self and other
(repr)Vector(5, 7) (repr)Vector(23, 35) (repr)Vector(0, 0)
(repr)Vector(28, 42)
(repr)Vector(15, 21)
(repr)Vector(230, 350)
True True
False
Vector(-1, 0):  True

 

매직 매소드만 재정의가 가능함, 매직 매소드에 없는 기능을 추가하면 정상동작하지 않음

 

# 오류발생, max 함수를 재정의방식으로 추가해도 동작하지 않는다
print(print(max(v1, v2)))
print()

# 정상동작함
print(Vector.__max__(v1,v2)) 
print(bool(v3))

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

Traceback (most recent call last):
  File "d:\workspace\Python\python_inter\p_study\p_chapter03_02.py", line 54, in <module>
    print(print(max(v1, v2)))
TypeError: '>' not supported between instances of 'Vector' and 'Vector'

(repr)Vector(23, 35) <== 정상출력됨
False

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

[Python] 고급 - 리스트 및 튜플(1)  (0) 2021.05.22
[Python] NamedTuple  (0) 2021.05.21
[Python] Magic Method(1)  (0) 2021.05.21
[Python] Class(3) - Class Method, Static Method  (0) 2021.05.21
[Python] Class(2) - self, 매직 매소드  (0) 2021.05.20