본문 바로가기

Python/Intermediate

[Python] Magic Method(1)

클래스 예제

 

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' 카테고리의 다른 글

[Python] NamedTuple  (0) 2021.05.21
[Python] Magic Method(2)  (0) 2021.05.21
[Python] Class(3) - Class Method, Static Method  (0) 2021.05.21
[Python] Class(2) - self, 매직 매소드  (0) 2021.05.20
[Python] Class(1) - Basic  (0) 2021.05.20