Hàm help trong Python được sử dụng để hiện thị tài liệu của các mô-đun, các hàm, các class, các từ khóa, v.v…

Hàm help có cú pháp như sau:

help([object])

Nếu hàm help được gọi mà không có đối số nào được truyền vào, thì tiện ích trợ giúp tương tác sẽ khởi động ở giao diện console.

Chúng ta cùng kiểm tra phần tài liệu của hàm print trong giao diện console của Python:

# -----------------------------------------------------------
#Cafedev.vn - Kênh thông tin IT hàng đầu Việt Nam
#@author cafedevn
#Contact: cafedevn@gmail.com
#Fanpage: https://www.facebook.com/cafedevn
#Instagram: https://instagram.com/cafedevn
#Twitter: https://twitter.com/CafedeVn
#Linkedin: https://www.linkedin.com/in/cafe-dev-407054199/
#

help(print) 

Kết quả in ra là:

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.
    Optional keyword arguments:
    file:  a file-like object (stream); defaults to the current sys.stdout.
    sep:   string inserted between values, default a space.
    end:   string appended after the last value, default a newline.
    flush: whether to forcibly flush the stream.

Kết quả đầu ra của hàm help cũng có thể được định nghĩa cho các hàm và class do người dùng tạo ra. Documentation string – viết tắt docstring được sử dụng để cung cấp thông tin về tài liệu. Nó được đặt bên trong cặp ba dấu nháy đơn (‘’’), và là câu lệnh đầu tiên được viết ở bên trong một class, một hàm, hoặc một mô-đun.

Xét ví dụ về class có các hàm như sau:


class Helper: 
    def __init__(self): 
        '''The helper class is initialized'''
  
    def print_help(self): 
        '''Returns the help description'''
        print('helper description') 
  
help(Helper) 
help(Helper.print_help) 

Khi chạy đoạn chương trình trên, chúng ta thấy được phần output của hàm help thứ nhất:

Help on class Helper in module __main__:

class Helper(builtins.object)
 |  Methods defined here:
 |  
 |  __init__(self)
 |      The helper class is initialized
 |  
 |  print_help(self)
 |      Returns the help description
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |  
 |  __dict__
 |      dictionary for instance variables (if defined)
 |  
 |  __weakref__
 |      list of weak references to the object (if defined)

Help on function print_help in module __main__:

print_help(self)
    Returns the help description

Nguồn và Tài liệu tiếng anh tham khảo:

Tài liệu từ cafedev:

Nếu bạn thấy hay và hữu ích, bạn có thể tham gia các kênh sau của cafedev để nhận được nhiều hơn nữa:

Chào thân ái và quyết thắng!

Đăng ký kênh youtube để ủng hộ Cafedev nha các bạn, Thanks you!