λ³Έλ¬Έ λ°”λ‘œκ°€κΈ°

Python

[Python] docstring (λ¬Έμ„œν™” / μ‚¬μš©μž μ •μ˜ ν•¨μˆ˜ )

λ°˜μ‘ν˜•

🎈 python docstring references: https://wikidocs.net/16050

 

24. Docstring - λ¬Έμ„œν™”

- νŒŒμ΄μ¬μ„ μ ‘ν•˜λ©΄μ„œ, μ—¬λŸ¬κ°€μ§€λ‘œ 멋지닀라고 μƒκ°ν–ˆλ˜ 것 쀑에 ν•˜λ‚˜ - docstring을 μž‘μ„±ν•˜λ©΄, ν”„λ‘œκ·Έλž˜λ°μ˜ μ†μ„±μœΌλ‘œ μ ‘κ·Όν• μˆ˜ 있음. ## 1. docstring μ΄λž€ …

wikidocs.net

  • docstring은 λͺ¨λ“ˆ, ν•¨μˆ˜, 클래슀 λ˜λŠ” λ©”μ†Œλ“œ μ •μ˜μ˜ 첫 번째 λͺ…λ Ήλ¬ΈμœΌλ‘œ λ°œμƒν•˜λŠ” λ¬Έμžμ—΄ λ¦¬ν„°λŸ΄
  • Module 첫번째 쀄, ν•¨μˆ˜ μ„ μ–Έ ν›„ λ‚΄λΆ€ λ°”λ‘œ μ•„λž«μ€„ λ˜λŠ” 클래슀 μ„ μ–Έ ν›„ λ‚΄λΆ€ λ°”λ‘œ μ•„λž«μ€„μ— ν°λ”°μ˜΄ν‘œ 3κ°œλ‚˜ μž‘μ€ λ”°μ˜΄ν‘œ 3개둜 μž‘μ„±ν•˜λ©΄ λœλ‹€.

 

πŸ– Docstring μ‚¬μš© μ˜ˆμ‹œ

def hello():
  """이 ν•¨μˆ˜λŠ” 'Hello World!'λ₯Ό 좜λ ₯ν•œλ‹€!"""
  print('Hello World!')
  
hello()

# Hello World!
# μ•„λž˜ ν˜•μ‹μ— λŒ€ν•΄μ„œλŠ” pep8 Guide μ°Έκ³  : https://peps.python.org/pep-0008/
def hello(name: str) -> None:    # None을 μ¨μ„œ 각각의 parameterκ°€ type을 따라가도둝 code μž…λ ₯을 받도둝
  if not isinstance(name, str):
    raise TypeError("Name Must be a String!")
  print(f"μ•ˆλ…•!,{name}")
  
hello("Lee")
# μ•ˆλ…•!,Lee

hello(123)
# TypeError: Name Must be a String!

 

πŸ‘€ Docstring 의 λ²”μš©μ„±

# λ²”μš©μ„±μ΄ λ–¨μ–΄μ§€λŠ” μ˜ˆμ‹œ
def add(a, b, c):
  return a + b + c

print(add(1, 2, 3))
# 6

print(add(1, 2))
# TypeError: add() missing 1 required positional argument: 'c'


# λ³΄μ™„λœ μ½”λ“œ - *args μ‚¬μš©
def add(*args):
  print(args, type(args))

add(1, 2, 3, 4, 5)
# (1, 2, 3, 4, 5) <class 'tuple'>


def add(*args):
  addition = 0
  for number in args:
    addition += number
  return addition

print(add(1, 2))
print(add(1, 2, 3))
print(add(1, 2, 3, 4))
# kwargs : dictionary ν˜•νƒœλ‘œ λ°›μŒ
# λ¨Έμ‹ λŸ¬λ‹ 클래슀, ν•˜μ΄νΌνŒŒλΌλ―Έν„° νŠœλ‹ μ‹œ, μž…λ ₯ 값을 dictionaryλ£° κΈ°λ³Έκ°’μœΌλ‘œ λ°›κΈ° λ•Œλ¬Έμ—
# => kwargs λ°˜λ“œμ‹œ μ •μ˜!
def temp(**kwargs):
  for key, value in kwargs.items():
    print(key, value)

temp(name="evan", age=30, city="Incheon")
λ°˜μ‘ν˜•