μ§μ μ μν ν΄λμ€μ κ°μ²΄μ
• +, - * μ κ°μ μΌλ° μ°μ°μλ₯Ό μ μ©νλ €λ©΄ , κ°μ²΄λ₯Ό μ°μ° κ°λ₯ν μνλ‘ λ§λ€μ΄μΌ ν¨
• μ°μ°μ μ€λ²λ‘λ©μ ν΅ν΄ μ΄λ₯Ό ꡬν
μ°μ°μ μ€λ²λ‘λ©
• μΈμ€ν΄μ€ κ°μ²΄λΌλ¦¬ μλ‘ μ°μ°μ ν μ μκ² κΈ°μ‘΄μ μλ μ°μ°μ μ κΈ°λ₯μ λ°κΎΈμ΄ μ€λ³΅μΌλ‘ μ μνλ κ²
νμ΄μ¬μμλ νΉμ μ΄λ¦μ λ©μλλ₯Ό μ¬μ μνλ©΄ μ°μ° μ μ€λ³΅μ μ ꡬν
μμ 1)
#μ°μ°μ μ€λ²λ‘λ© μμ 1
class NumBox:
def __init__(self,num):
self.num = num
def __add__(self, num):
self.num += num
def __sub__(self, num):
self.num -= num
n = NumBox(40)
n + 100 # n+100 == n.__add__
print(n.num)
n-100
print(n.num)
μμ 2)
#μ°μ°μ μ€λ²λ‘λ© 2
#self : κ°μ²΄ μμ
# other : λνκ³ μ νλ κ°
class Number:
def __init__(self,n):
self.n = n
n1 = Number(3)
n2 = Number(4)
### μλ μλ¬λλ μ μ½λ, μλλ λ³κ²½ μ½λ ###
class Number:
def __init__(self,n):
self.n = n
def __add__(self, other):
if isinstance(other, Number):
return Number(self.n +other.n)
elif isinstance(other, int):
return Number(self.n + other)
n1 = Number(3)
n2 = Number(4)
print(n1+n2)
# <__main__.Number object at 0x03248040>
print((n1+n2).n)
print(n1 + 3)
# <__main__.Number object at 0x03248058>
print((n1 + 3).n)
λΉκ΅ μ°μ°μ μ€λ²λ‘λ© λ©μλ
λΉκ΅ μ°μ°μ μ€λ²λ‘λ© μμ)
class Number:
def __init__(self,n):
self.n = n
def __lt__(self, other):
return self.n < other.n
def __le__(self, other):
return self.n <= other.n
def __gt__(self, other):
return self.n > other.n
def __ge__(self, other):
return self.n <= other.n
def __eq__(self, other):
return self.n == other.n
n1 = Number(3)
n2 = Number(4)
print('n1 < n2 : {}'.format(n1<n2))
print('n1 <= n2 : {}'.format(n1<=n2))
print('n1 > n2 : {}'.format(n1>n2))
print('n1 <= n2 : {}'.format(n1<=n2))
print('n1 == n2 : {}'.format(n1==n2))