μ½”λ“œ - 패캠 μˆ˜μ—… μ½”λ“œ μ°Έκ³  (패캠 μˆ˜μ—… 정리)

 

<이전 κΈ€>

https://silvercoding.tistory.com/21

 

[python 심화] 4. 데이터 λͺ¨λΈ(Data Model), Nametuple

μ½”λ“œ - 패캠 μˆ˜μ—… μ½”λ“œ μ°Έκ³  (패캠 μˆ˜μ—… 정리) <이전 κΈ€> https://silvercoding.tistory.com/20 https://silvercoding.tistory.com/19 https://silvercoding.tistory.com/18 [python 심화] 1. 객체지ν–₯(OOP), 클..

silvercoding.tistory.com

 

 

<맀직 λ©”μ†Œλ“œ κ΄€λ ¨ λ¬Έμ„œ>

https://docs.python.org/3/reference/datamodel.html#special-method-names

 

3. Data model — Python 3.9.6 documentation

A class can implement certain operations that are invoked by special syntax (such as arithmetic operations or subscripting and slicing) by defining methods with special names. This is Python’s approach to operator overloading, allowing classes to define

docs.python.org

https://www.tutorialsteacher.com/python/magic-methods-in-python

 

Magic or Dunder Methods in Python

Python - Magic or Dunder Methods Magic methods in Python are the special methods that start and end with the double underscores. They are also called dunder methods. Magic methods are not meant to be invoked directly by you, but the invocation happens inte

www.tutorialsteacher.com

파이썬의 μ€‘μš”ν•œ 핡심 ν”„λ ˆμž„ μ›Œν¬ : μ‹œν€€μŠ€(Sequence), 반볡(Iterator), ν•¨μˆ˜(Functions), 클래슀(Class

 

 

 

- λ§€μ§λ©”μ†Œλ“œ 

n = 100 
print(dir(n)) # λͺ¨λ“  속성 및 λ©”μ†Œλ“œ 좜λ ₯ 

__xxx__ ----> 맀직 λ©”μ†Œλ“œ 

 

 

*** μ‚¬μš© 

print('EX1-1 - ', n + 200)
print('EX1-2 - ', n.__add__(200))
print('EX1-3 - ', n.__doc__)
print('EX1-4 - ', n.__bool__(), bool(n))
print('EX1-5 - ', n * 100, n.__mul__(100))

맀직 λ©”μ†Œλ“œλŠ” νŒŒμ΄μ¬μ—μ„œ 이미 μ •μ˜λœ λ©”μ„œλ“œλΌκ³  보면 λœλ‹€. 이보닀도 더 λ‹€μ–‘ν•œ 맀직 λ©”μ†Œλ“œλ“€μ΄ μžˆλ‹€. 

μ΄λŸ¬ν•œ μ •μˆ˜ν˜• νƒ€μž…μ˜ κ°μ²΄λŠ” κ·Έλƒ₯ + , * μ΄λŸ¬ν•œ κΈ°ν˜Έλ“€λ‘œ μ‚¬μš©ν•  수 μžˆκ² μ§€λ§Œ, 직접 클래슀λ₯Ό λ§Œλ“€μ–΄ μ‚¬μš©ν•  λ•ŒλŠ” 직접 μ •μ˜λ₯Ό ν•΄μ„œ μœ μš©ν•˜κ²Œ μ‚¬μš©ν•  수 μžˆλ‹€. 

 

 

 

 

- 클래슀 맀직 λ©”μ†Œλ“œ 예제 

(1) 클래슀 생성 

class Student:
    # 맀직 λ©”μ„œλ“œμž„. νŒŒμ΄μ¬μ—μ„œ 이미 μ •μ˜λœ λ©˜μ„œλ“œ 
    def __init__(self, name, height):
        self._name = name
        self._height = height

    def __str__(self):
        return 'Student Class Info : {}, {}'.format(self._name, self._height)

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

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

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

 

μœ„μ˜ λ¬Έμ„œμ—μ„œ κ°€μ Έμ˜¨ 맀직 λ©”μ„œλ“œ 의미 

__str__ ---> To get called by built-int str() method to return a string representation of a type.

__le__ ---> To get called on comparison using <= operator.

__ge__ ---> To get called on comparison using >= operator.

__sub__ ---> To get called on subtraction operation using - operator.

 

 

(2) μ‚¬μš© 

*** μΈμŠ€ν„΄μŠ€ 생성 

s1 = Student('James', 181)
s2 = Student('Mie', 165)

Student 클래슀의 μΈμŠ€ν„΄μŠ€ 생성!

 

*** 맀직 λ©”μ†Œλ“œ 좜λ ₯ 

print('EX2-1 - ', s1 >= s2)
print('EX2-2 - ', s1 <= s2)
print('EX2-3 - ', s1 - s2)
print('EX2-4 - ', s2 - s1)
print('EX2-5 - ', s1)
print('EX2-6 - ', s2)

ν΄λž˜μŠ€μ— λ§€μ§λ©”μ†Œλ“œλ₯Ό μ •μ˜ν•˜μ§€ μ•Šμ•˜λ‹€λ©΄ 객체와 κ°μ²΄κ°„μ˜ λΉ„κ΅λ‘œ 받아듀이기 λ•Œλ¬Έμ— 였λ₯˜κ°€ λ‚œλ‹€. 

ν΄λž˜μŠ€μ—μ„œ 직접 μ •μ˜λ₯Ό ν•΄λ†¨μœΌλ―€λ‘œ 였λ₯˜κ°€ λ‚˜μ§€ μ•Šκ³  μ •μ˜ν•œ λŒ€λ‘œ λ‚˜μ˜¨λ‹€. 

이와같이 λ§€μ§λ©”μ†Œλ“œλ₯Ό 직접 μ •μ˜ν•˜μ—¬ μœ μš©ν•œ ν™œμš©μ΄ κ°€λŠ₯ν•˜λ‹€. 

 

 

 

- 클래슀 λ©”μ§λ©”μ†Œλ“œ μ‚¬μš© 예제 2

(1) 클래슀 생성 

class Vector(object):
    def __init__(self, *args):
        '''Create a vector, example : v = Vector(1, 2)'''
        if len(args) == 0:
            self._x, self._y = 0, 0
        else:
            self._x, self._y = args

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

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

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

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

벑터λ₯Ό μƒμ„±ν•΄μ£ΌλŠ” ν΄λž˜μŠ€μ΄λ‹€. 

__add__λ©”μ†Œλ“œλŠ” 벑터끼리 각 μ’Œν‘œμ— λŒ€ν•œ λ§μ…ˆ, __mul__λ©”μ†Œλ“œλŠ” μ‹€μˆ˜λ₯Ό μΈμžμ— λ„£μ–΄μ£Όλ©΄ 각 μ’Œν‘œμ— κ³±ν•΄μ§€λŠ” 것을 κ΅¬ν˜„ν•œ 것이닀. __bool__λ©”μ†Œλ“œλŠ” x, y μ’Œν‘œ 쀑 큰 값이 0이 μ•„λ‹ˆλ©΄ Trueλ₯Ό λ°˜ν™˜ν•˜κ²Œ ν•΄μ€€λ‹€. (정말 κ΅¬ν˜„ν•˜κ³  싢은 λŒ€λ‘œ κ΅¬ν˜„ν•˜λ©΄ λœλ‹€!)

 

 

(2) μ‚¬μš© 

# Vector μΈμŠ€ν„΄μŠ€ 생성
v1 = Vector(3, 5)
v2 = Vector(15, 20)
v3 = Vector()

# 맀직 λ©”μ†Œλ“œ 좜λ ₯ 
print("EX3-1 - ", Vector.__init__.__doc__)
print("EX3-2 - ", Vector.__repr__.__doc__)
print("EX3-3 - ", Vector.__add__.__doc__)
print("EX3-4 - ", v1, v2, v3)
print("EX3-5 - ", v1 + v2)
print("EX3-6 - ", v1 * 4)
print("EX3-7 - ", v2 * 10)
print('EX3-8 - ', bool(v1), bool(v2))
print('EX3-9 - ', bool(v3))

__doc__ λ₯Ό μ‚¬μš©ν•˜λ©΄ μœ„μ—μ„œ μž‘μ„±ν–ˆλ˜ 주석 μ„€λͺ…이 좜λ ₯λœλ‹€. λ‚˜λ¨Έμ§€λ„ 잘 μ‹€ν–‰λ˜λ©΄ 성곡!

 

 

 

 

 

 

 

 

 

 

 

 

 

 

+ Recent posts