logo

Python 독스트링

깨끗하고 잘 문서화된 코드를 작성하는 데 있어 Python 개발자는 독스트링이라는 비밀 무기를 사용할 수 있습니다. 문서 문자열의 약자인 Docstring은 문서의 목적과 기능을 전달하는 데 매우 중요합니다. 파이썬 함수, 모듈, 클래스.

Python의 독스트링(Docstring)이란 무엇입니까?

파이썬 문서 문자열(또는 독스트링)은 문서를 다음과 연결하는 편리한 방법을 제공합니다. Python 모듈 , 함수, 클래스 및 메서드. 이는 주석과 같이 특정 코드 세그먼트를 문서화하는 데 사용되는 소스 코드에 지정됩니다. 기존 소스 코드 주석과 달리 독스트링은 함수가 수행하는 작업이 아닌 무엇을 수행하는지 설명해야 합니다.



  • 독스트링 선언 : 독스트링은 클래스, 메소드 또는 함수 선언 바로 아래에 '세 개의 작은따옴표' 또는 세 개의 큰따옴표를 사용하여 선언됩니다. 모든 함수에는 독스트링이 있어야 합니다.
  • 독스트링에 접근하기 : 독스트링은 객체의 __doc__ 메소드나 도움말 함수를 사용하여 접근할 수 있습니다. 아래 예제는 독스트링을 선언하고 액세스하는 방법을 보여줍니다.

독스트링은 어떤 모습이어야 할까요?

  • 문서 문자열 줄은 대문자로 시작하고 마침표로 끝나야 합니다.
  • 첫 번째 줄은 간단한 설명이어야 합니다.
  • 문서 문자열에 더 많은 줄이 있는 경우 두 번째 줄은 비어 있어야 하며 요약과 나머지 설명을 시각적으로 구분해야 합니다.
  • 다음 줄은 객체의 호출 규칙, 부작용 등을 설명하는 하나 이상의 단락이어야 합니다.

Python의 독스트링

이 기사에서 다룰 주제는 다음과 같습니다.

  • 삼중따옴표로 묶인 문자열
  • Google 스타일 Docstring
  • Numpydoc 스타일 Docstring
  • 한 줄 독스트링
  • 여러 줄 독스트링
  • Docstring의 들여쓰기
  • 클래스의 독스트링
  • Python 주석과 Docstring의 차이점

삼중따옴표로 묶인 문자열

이것은 Python에서 가장 일반적인 Docstring 형식입니다. 문서 텍스트를 묶기 위해 삼중따옴표(작은따옴표 또는 큰따옴표)를 사용하는 것이 포함됩니다. 삼중따옴표로 묶인 문자열은 여러 줄에 걸쳐 있을 수 있으며 함수, 클래스 또는 모듈 정의 바로 아래에 배치되는 경우가 많습니다.

예시 1: 세 개의 작은따옴표 사용



파이썬3






자바 하위 문자열에 다음이 포함되어 있습니다.
def> my_function():> >'''Demonstrates triple double quotes> >docstrings and does nothing really.'''> > >return> None> print>(>'Using __doc__:'>)> print>(my_function.__doc__)> print>(>'Using help:'>)> help>(my_function)>

>

>

산출:

Using __doc__: Demonstrates triple double quotes docstrings and does nothing really. Using help: Help on function my_function in module __main__: my_function() Demonstrates triple double quotes docstrings and does nothing really.>

예시 2: 삼중큰따옴표 사용

파이썬3




def> my_function():> >' '> 'Demonstrates triple double quotes docstrings and does nothing really'> ' '> > >return> None> print>(>'Using __doc__:'>)> print>(my_function.__doc__)> print>(>'Using help:'>)> help>(my_function)>

>

>

산출:

Using __doc__: Demonstrates triple double quotes docstrings and does nothing really. Using help: Help on function my_function in module __main__: my_function() Demonstrates triple double quotes docstrings and does nothing really.>

Google 스타일 Docstring

Google 스타일 독스트링은 특정 형식을 따르며 Google의 문서 스타일 가이드에서 영감을 받았습니다. 매개변수, 반환 값, 설명을 포함하여 Python 코드를 문서화하는 구조화된 방법을 제공합니다.

파이썬3




def> multiply_numbers(a, b):> >'''> >Multiplies two numbers and returns the result.> >Args:> >a (int): The first number.> >b (int): The second number.> >Returns:> >int: The product of a and b.> >'''> >return> a>*> b> print>(multiply_numbers(>3>,>5>))>

>

자바를 인쇄하는 방법
>

산출

15>

Numpydoc 스타일 Docstring

Numpydoc 스타일의 독스트링은 과학 및 데이터 분석 커뮤니티, 특히 수치 계산 및 데이터 조작과 관련된 함수 및 클래스를 문서화하는 데 널리 사용됩니다. 이는 매개변수 및 반환 값을 문서화하기 위한 몇 가지 추가 규칙이 포함된 Google 스타일 Docstring의 확장입니다.

파이썬3




def> divide_numbers(a, b):> >'''> >Divide two numbers.> >Parameters> >----------> >a : float> >The dividend.> >b : float> >The divisor.> >Returns> >-------> >float> >The quotient of the division.> >'''> >if> b>=>=> 0>:> >raise> ValueError(>'Division by zero is not allowed.'>)> >return> a>/> b> print>(divide_numbers(>3>,>6>))>

>

>

산출

0.5>

한 줄 독스트링

이름에서 알 수 있듯이, 한 줄 독스트링은 한 줄에 맞습니다. 명백한 경우에 사용됩니다. 닫는 따옴표는 시작 따옴표와 같은 줄에 있습니다. 이것은 단일 라이너에 더 좋아 보입니다. 예를 들어:

파이썬3




def> power(a, b):> >' '> 'Returns arg1 raised to power arg2.'> ' '> > >return> a>*>*>b> print>(power.__doc__)>

>

>

arp-a 명령

산출:

Returns arg1 raised to power arg2.>

여러 줄 독스트링

여러 줄 독스트링은 한 줄 독스트링과 마찬가지로 요약 줄, 빈 줄, 더 자세한 설명으로 구성됩니다. 요약 줄은 시작 인용문과 같은 줄이나 다음 줄에 있을 수 있습니다. 아래 예는 여러 줄의 독스트링을 보여줍니다.

파이썬3




데이터 수집
def> add_numbers(a, b):> >'''> >This function takes two numbers as input and returns their sum.> >Parameters:> >a (int): The first number.> >b (int): The second number.> >Returns:> >int: The sum of a and b.> >'''> >return> a>+> b> print>(add_numbers(>3>,>5>))>

>

>

산출:

8>

Docstring의 들여쓰기

전체 독스트링은 첫 번째 줄의 따옴표와 동일하게 들여쓰기됩니다. 독스트링 처리 도구는 독스트링의 두 번째 줄과 그 다음 줄에서 균일한 양의 들여쓰기를 제거합니다. 이는 첫 번째 줄 뒤의 공백이 아닌 모든 줄의 최소 들여쓰기와 동일합니다. 독스트링의 첫 번째 줄(즉, 첫 번째 새 줄까지)의 들여쓰기는 중요하지 않으며 제거됩니다. 독스트링에서 뒷줄의 상대 들여쓰기는 유지됩니다.

파이썬3




class> Employee:> >'''> >A class representing an employee.> >Attributes:> >name (str): The name of the employee.> >age (int): The age of the employee.> >department (str): The department the employee works in.> >salary (float): The salary of the employee.> >'''> >def> __init__(>self>, name, age, department, salary):> >'''> >Initializes an Employee object.> >Parameters:> >name (str): The name of the employee.> >age (int): The age of the employee.> >department (str): The department the employee works in.> >salary (float): The salary of the employee.> >'''> >self>.name>=> name> >self>.age>=> age> >self>.department>=> department> >self>.salary>=> salary> >def> promote(>self>, raise_amount):> >'''> >Promotes the employee and increases their salary.> >Parameters:> >raise_amount (float): The raise amount to increase the salary.> >Returns:> >str: A message indicating the promotion and new salary.> >'''> >self>.salary>+>=> raise_amount> >return> f>'{self.name} has been promoted! New salary: ${self.salary:.2f}'> >def> retire(>self>):> >'''> >Marks the employee as retired.> >Returns:> >str: A message indicating the retirement status.> >'''> ># Some implementation for retiring an employee> >return> f>'{self.name} has retired. Thank you for your service!'> # Access the Class docstring using help()> help>(Employee)>

>

>

산출:

class Employee | A class representing an employee. | | Attributes: | name (str): The name of the employee. | age (int): The age of the employee. | department (str): The department the employee works in. | salary (float): The salary of the employee. | | Methods defined here: | | __init__(self, name, age, department, salary) | Initializes an Employee object. | | Parameters: | name (str): The name of the employee. | age (int): The age of the employee. | department (str): The department the employee works in. | salary (float): The salary of the employee. | | promote(self, raise_amount) | Promotes the employee and increases their salary. | | Parameters: | raise_amount (float): The raise amount to increase the salary. | | Returns: | str: A message indicating the promotion and new salary. | | retire(self) | Marks the employee as retired. | | Returns: | str: A message indicating the retirement status.>

클래스의 독스트링

클래스와 메소드에 대한 독스트링을 작성하는 방법을 보여주는 예를 들어보겠습니다. 돕다' docstring에 액세스하는 데 사용됩니다.

파이썬3




class> ComplexNumber:> >'''> >This is a class for mathematical operations on complex numbers.> >Attributes:> >real (int): The real part of the complex number.> >imag (int): The imaginary part of the complex number.> >'''> >def> __init__(>self>, real, imag):> >'''> >The constructor for ComplexNumber class.> >Parameters:> >real (int): The real part of the complex number.> >imag (int): The imaginary part of the complex number.> >'''> >self>.real>=> real> >self>.imag>=> imag> >def> add(>self>, num):> >'''> >The function to add two Complex Numbers.> >Parameters:> >num (ComplexNumber): The complex number to be added.> >Returns:> >ComplexNumber: A complex number which contains the sum.> >'''> >re>=> self>.real>+> num.real> >im>=> self>.imag>+> num.imag> >return> ComplexNumber(re, im)> # Access the Class docstring using help()> help>(ComplexNumber)> # Access the method docstring using help()> help>(ComplexNumber.add)>

>

>

산출:

Help on class ComplexNumber in module __main__: class ComplexNumber(builtins.objects) | This is a class for mathematical operations on complex numbers. | | Attributes: | real (int): The real part of complex number. | imag (int): The imaginary part of complex number. | | Methods defined here: | | __init__(self, real, imag) | The constructor for ComplexNumber class. | | Parameters: | real (int): The real part of complex number. | imag (int): The imaginary part of complex number. | | add(self, num) | The function to add two Complex Numbers. | | Parameters: | num (ComplexNumber): The complex number to be added. | | Returns: | ComplexNumber: A complex number which contains the sum. Help on method add in module __main__: add(self, num) unbound __main__.ComplexNumber method The function to add two Complex Numbers. Parameters: num (ComplexNumber): The complex number to be added. Returns: ComplexNumber: A complex number which contains the sum.>

Python 주석, 문자열 및 Docstring의 차이점

문자열: Python에서 문자열은 작은따옴표(' ') 또는 큰따옴표( )로 묶인 일련의 문자입니다. 문자열은 텍스트 데이터를 나타내는 데 사용되며 문자, 숫자, 기호 및 공백을 포함할 수 있습니다. 이는 Python의 기본 데이터 유형 중 하나이며 다양한 문자열 방법을 사용하여 조작할 수 있습니다.

여러분 모두 Python 독스트링에 대한 아이디어를 갖고 있을 것입니다. 하지만 Python 주석과 독스트링의 차이점이 무엇인지 궁금한 적이 있습니까? 그것들을 살펴보자.

독자가 소스 코드를 이해할 수 있도록 개발자가 제공하는 유용한 정보입니다. 코드에 사용된 논리 또는 그 일부를 설명합니다. 을 사용하여 작성됩니다.

#>

기호.

예:

파이썬3




# Python program to demonstrate comments> print>(>'GFG'>)> name>=> 'Abhishek Shakya'> #demostrate String>

자바 람다

>

>

산출:

GFG>

위에서 언급한 Python Docstring은 문서를 Python 모듈, 함수, 클래스 및 메서드와 연결하는 편리한 방법을 제공합니다.