Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Python help(): เรียกดูเอกสารและความช่วยเหลือภายในโปรแกรม

ฟังก์ชัน help() เป็น Built-in Function ที่ให้เข้าถึง Interactive Help System และเอกสาร (Docstrings) ของ Objects, Modules, Functions, Classes, Keywords ได้ภายใน Python Interpreter โดยไม่ต้องออกไปหาเว็บไซต์

ไวยากรณ์

help([object])
help('topic')  # String topic

โหมดการใช้งาน

1. Interactive Mode (ใน REPL)

>>> help()
# เข้าสู่ Help Utility
help> print
help> modules
help> keywords
help> topics
help> quit

2. Programmatic Mode (ใน Script)

# พิมพ์ Help ของ Object ลง Console
print(help('print'))
print(help(len))
print(help(list))
print(help('modules'))  # รายชื่อ Modules

ตัวอย่างการใช้งาน

ช่วยเหลือเกี่ยวกับ Built-in Functions

print(help('print'))
# Help on built-in function print in module builtins:
# print(...)
#     print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
#     Prints the values to a stream, or to sys.stdout by default.

ช่วยเหลือเกี่ยวกับ Modules

print(help('math'))
# Help on module math:
# NAME
#     math
# DESCRIPTION
#     This module provides access to the mathematical functions...
# FUNCTIONS
#     acos(x) -> Return the arc cosine of x.
#     ...
#     sqrt(x) -> Return the square root of x.

ช่วยเหลือเกี่ยวกับ Classes/Methods

print(help(str))
print(help(str.split))
print(help(list.append))

ช่วยเหลือเกี่ยวกับ Keywords/Topics

print(help('if'))
print(help('for'))
print(help('exceptions'))
print(help('LOOPING'))

การเขียน Docstring ให้ Help() แสดงผล

Docstring (Triple-quoted String ด้านบน Function/Class/Module) จะถูก Help() แสดงโดยอัตโนมัติ

def calculate_area(radius):
    """Calculate the area of a circle.
    
    Args:
        radius (float): The radius of the circle.
    
    Returns:
        float: The area of the circle (π * r²).
    
    Example:
        >>> calculate_area(5)
        78.53981633974483
    """
    import math
    return math.pi * radius ** 2

# ทดสอบ
print(help(calculate_area))

การเข้าถึง Docstring โดยตรง

# __doc__ Attribute
print(calculate_area.__doc__)
print(len.__doc__)
print(list.__doc__)

เครื่องมือช่วยเหลือเพิ่มเติม

dir() - รายชื่อ Attributes

print(dir(str))      # Methods ของ String
print(dir(math))     # Functions ใน Math Module

inspect Module - รายละเอียดลึก

import inspect

print(inspect.signature(calculate_area))
# (radius)

print(inspect.getsource(calculate_area))
# ดู Source Code ของ Function

print(inspect.getfile(math))
# Path ของ Math Module

pydoc Command Line

# ใน Terminal
python -m pydoc math
python -m pydoc -w math  # Generate HTML
python -m pydoc -p 8080  # Start HTTP Server

สรุป

  • help() เป็นเครื่องมือ Built-in สำหรับอ่านเอกสารทันที
  • ใช้ help('topic') สำหรับ String Topic, help(object) สำหรับ Object
  • เขียน Docstring ให้ครบถ้วน (Args, Returns, Example) จะช่วยทีมและ Future You
  • ร่วมกับ dir(), inspect, pydoc จะได้ข้อมูลครบถ้วน