Important Notice:

DocStrings in Python

DocStrings in Python

17 views 2 min read

DocStrings in Python :-

 Python में DocString (Documentation String) एक विशेष प्रकार की string होती है, जिसका उपयोग function, class या module के उद्देश्य और कार्य को समझाने के लिए किया जाता है। इसे संबंधित code block की शुरुआत में triple quotes (""" """ या ''' ''') के अंदर लिखा जाता है।

Python में DocString को display किया जा सकता है। इसके लिए __doc__ attribute या help() function का उपयोग किया जाता है।

English Definition: A DocString (Documentation String) is a string used to describe the purpose and functionality of a function, class, or module in Python. It is written at the beginning of the corresponding code block using triple quotes.

In Python, a DocString can be displayed using the __doc__ attribute or the help() function.

note-

Python Interpreter Docstring को Comment की तरह Ignore नहीं करता, बल्कि उसे Program की Documentation के रूप में सुरक्षित (Store) रखता है। बाद में हम इसे __doc__ से देख सकते हैं:

print(function_name.__doc__)

Example:

def greet():
    """This function displays a greeting message."""
    print("Hello, Python!")


greet()
print(greet.__doc__)
help(greet)

Output:

Hello, Python!
This function displays a greeting message.
Help on function greet in module __main__:

greet()
    This function displays a greeting message.

Explanation:

  • greet() एक function है।

  • """This function displays a greeting message.""" इसका DocString है।

  • DocString बताता है कि function क्या काम करता है।

  • DocString स्वयं सामान्यतः screen पर display नहीं होता।

  • Python में DocString को display किया जा सकता है।

याद रखें:

  • greet() → Function का काम execute करता है।

  • greet.__doc__ → केवल DocString प्राप्त करता है।

  • help(greet) → Function की documentation दिखाता है।

इसलिए तीनों का output अलग-अलग है, क्योंकि तीनों का काम अलग है।

 

Example 2: Multi-Line DocString

def calculate_square(number):
    """
    Calculate the square of a number.

    Parameter:
        number: The number whose square is calculated.

    Returns:
        The square of the given number.
    """
    return number * number

print(calculate_square(5))

Output:

25

Explanation:

  • पहली line function का उद्देश्य बताती है।

  • Parameter section input parameter के बारे में बताता है।

  • Returns section वापस मिलने वाली value बताता है।

  • Multi-line DocString में function की जानकारी विस्तार

Related Notes