🐹 μŠ€νŽ˜μ…œ λ©”μ„œλ“œ

λ―Όλ‹¬νŒ½μ΄μš°μœ Β·2024λ…„ 6μ›” 2일

🐹 파이썬 기초

λͺ©λ‘ 보기
18/19

πŸ’‘ 1. μŠ€νŽ˜μ…œ λ©”μ„œλ“œ

파이썬의 μŠ€νŽ˜μ…œ λ©”μ„œλ“œ (λ˜λŠ” 맀직 λ©”μ„œλ“œλΌκ³ λ„ 뢈림)λŠ” 더블 μ–Έλ”μŠ€μ½”μ–΄(__)둜 μ‹œμž‘ν•˜κ³  λλ‚˜λŠ” λ©”μ„œλ“œ 이름을 κ°–λŠ”λ‹€. 이 λ©”μ„œλ“œλ“€μ€ νŠΉμ • κ΅¬λ¬Έμ΄λ‚˜ λ‚΄μž₯ ν•¨μˆ˜λ₯Ό μ‚¬μš©ν•  λ•Œ 파이썬 인터프리터에 μ˜ν•΄ μžλ™μœΌλ‘œ ν˜ΈμΆœλœλ‹€.

class Book:
  def __init__(self, title):
    self.title = title
book = Book('μ–΄λ–»κ²Œ ν–„μŠ€ν„°κ°€ 개발자')
print(book)
print(str(book)) # print μ•ˆμ— str()이 μƒλž΅λλ‹€κ³  λ³Ό 수 μžˆλ‹€. str()은 λ¬Έμžμ—΄λ‘œ λ³€ν™˜ν•΄μ£ΌλŠ” κΈ°λŠ₯을 κ°–μ§€λ§Œ, 객체λ₯Ό λ„£μœΌλ©΄ 객체의 정보λ₯Ό 보여쀀닀
> <__main__.Book object at 0x7a2a1eec0220>
> <__main__.Book object at 0x7a2a1eec0220>
class Book:
  def __init__(self, title):
    self.title = title
  def __str__(self): # 파이썬 λ‚΄μ˜ str()ν•¨μˆ˜λ₯Ό μ˜€λ²„λΌμ΄λ”© (이 클래슀 ν•œμ •)
    return self.title
book = Book('μ–΄λ–»κ²Œ ν–„μŠ€ν„°κ°€ 개발자')
print(book)
print(str(book))
> μ–΄λ–»κ²Œ ν–„μŠ€ν„°κ°€ 개발자
> μ–΄λ–»κ²Œ ν–„μŠ€ν„°κ°€ 개발자
li = [1, 2, 3]
print(li) # liλŠ” 객체인데 정보가 μ•„λ‹ˆλΌ μ•ˆμ˜ 데이터가 좜λ ₯됨. 즉 list의 클래슀의 __str__에 리슀트 μ•ˆμ˜ μš”μ†Œλ₯Ό 좜λ ₯ν•  수 μžˆλ„λ‘ μ˜€λ²„λΌμ΄λ”© 돼있음
print(str(li))
> [1, 2, 3]
> [1, 2, 3]
class Calc:
  def __init__(self, num):
    self.num = num

  def __add__(self, other): # + 기호λ₯Ό μ˜€λ²„λΌμ΄λ”©
    return self.num + other.num
num1 = Calc(5)
num2 = Calc(10)
print(num1 + num2) # 객체의 μš”μ†Œ κ°„ λ§μ…ˆμ΄ κ°€λŠ₯ν•˜κ²Œ 함
> 15
class Queue:
  def __init__(self):
    self.items = [1, 2, 3, 4, 5]

  def __len__(self): # len() ν•¨μˆ˜ μ˜€λ²„λΌμ΄λ”©
    return len(self.items)
li = [1, 2, 3, 4, 5]
print(len(li))
> 5
queue = Queue()
print(queue) # str()을 μ˜€λ²„λΌμ΄λ”© μ‹œν‚€μ§€ μ•Šμ•„μ„œ 정보가 λ‚˜μ˜΄
print(len(queue)) # len() ν•¨μˆ˜λ₯Ό κ°μ²΄μ—μ„œλ„ μ“Έ 수 있게 함
> <__main__.Queue object at 0x7a2a1ebf1810>
> 5
class Queue:
  def __init__(self):
    self.items = [1, 2, 3, 4, 5]
queue = Queue()
print(queue) # str()을 μ˜€λ²„λΌμ΄λ”© μ‹œν‚€μ§€ μ•Šμ•„μ„œ 정보가 λ‚˜μ˜΄
print(len(queue))
> TypeError: object of type 'Queue' has no len()
> 3 len()을 μ˜€λ²„λΌμ΄λ”© ν•˜μ§€ μ•ŠμœΌλ©΄ 클래슀 κ°ν…Œμ˜ len을 ꡬ할 수 μ—†μŒ
class Point:
  def __init__(self, x, y):
    self.x = x
    self.y = y

  def __getitem__(self, index): # 인덱싱할 λ•Œ 호좜(인덱싱 μ˜€λ²„λΌμ΄λ”©)
    if index == 0:
      return self.x
    elif index == 1:
      return self.y
    else:
      return -1
pt = Point(5, 3)
print(pt[0])
print(pt[1])
print(pt[2])
> 5
> 3
> -1
profile
μ–΄λ–»κ²Œ ν–„μŠ€ν„°κ°€ 개발자

0개의 λŒ“κΈ€