newhaneul

[Advanced Python Programming] Lecture 7. Special Methods 본문

4. University Study/Advanced Python Programming

[Advanced Python Programming] Lecture 7. Special Methods

뉴하늘 2026. 4. 12. 22:54
728x90

포스팅은 인하대학교 허혜선 교수님의 [202601-EEC3408-001] 고급파이썬프로그래밍을 수강하고 공부한 내용을 정리하기 위한 포스팅입니다.

 

  • Special Methods
    • 파이썬에는 객체에 대하여 +, -, *, /와 같은 연산을 적용하도록 돕는 특수 메소드(special method)가 있다.
      • x + y: __add__(self, y)
      • x - y: __sub__(self, y)
      • x * y: __mul__(self, y)
      • x / y: __truediv__(self, y)
      • x // y: __floordiv__(self, y)
      • x % y: __mod__(self, y)
      • x ** y: __pow__(self, y)
      • x > y: __gt__(self, y)
      • x >= y: __ge__(self, y)
      • x < y: __lt__(self, y)
      • x <= y: __le__(self, y)
      • x == y: __eq__(self, y)
      • x != y: __ne__(self, y)

 

LAB: Vector 2D

class Vector2D:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __add__(self, other):
        return Vector2D(self.x + other.x, self.y + other.y)

    def __Sub__(self, other):
        return Vector2D(self.x - other.x, self.y - other.y)

    def __eq__(self, other):
        return self.x == other.x and self.y == other.y

    def __str__(self):
        return f'({self.x}, {self.y})'

u = Vector2D(0, 1)
v = Vector2D(1, 0)
w = Vector2D(1, 1)
a = u + v
print(a)

 

 

LAB: 주사위 클래스

from random import randint

class Dice:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.value = 1
        self.size = 30
    
    def read_dice(self):
        return self.value
    
    def print_dice(self):
        print('주사위 값 = ', self.value)

    def roll_dice(self):
        self.value = randint(1, 6)
    
d = Dice(100, 100)
d.roll_dice()
d.print_dice()

주사위 값 =  5
728x90