Get help in python

Python help() Method

The Python help() function invokes the interactive built-in help system. If the argument is a string, then the string is treated as the name of a module, function, class, keyword, or documentation topic, and a help page is printed on the console. If the argument is any other kind of object, a help page on the object is displayed.

Syntax:

Parameters:

object: (Optional) The object whose documentation needs to be printed on the console.

Return Vype:

The following displays the help on the builtin print method on the Python interactive shell.

>>> 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.
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.

Above, the specified string matches with the built-in print function, so it displays help on it.

The following displays the help page on the module.

>>> help(‘math’)
Help on built-in module math:

DESCRIPTION
This module is always available. It provides access to the
mathematical functions defined by the C standard.

FUNCTIONS
acos(x, /)
Return the arc cosine (measured in radians) of x.

acosh(x, /)
Return the inverse hyperbolic cosine of x.

asin(x, /)
Return the arc sine (measured in radians) of x.

asinh(x, /)
Return the inverse hyperbolic sine of x.

atan(x, /)
Return the arc tangent (measured in radians) of x.
— More —

Above, the specified string matches with the Math module, so it displays the help of the Math functions. — More — means there is more information to display on this by pressing the Enter or space key.

Interactive Help

If no argument is given, the interactive help system starts on the interpreter console, where you can write any function, module names to get the help, as shown below.

>>> help()
Welcome to Python 3.7’s help utility!

If this is your first time using Python, you should definitely check out
the tutorial on the Internet at https://docs.python.org/3.7/tutorial/.

Enter the name of any module, keyword, or topic to get help on writing
Python programs and using Python modules. To quit this help utility and
return to the interpreter, just type «quit».

To get a list of available modules, keywords, symbols, or topics, type
«modules», «keywords», «symbols», or «topics». Each module also comes
with a one-line summary of what it does; to list the modules whose name
or summary contain a given string such as «spam», type «modules spam».

Now, you can write anything to get help on. For example, write print to get help on the print function.

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.
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.

Help on Classes

The help function can also be used on built-in or user-defined classes and functions.

Help on class int in module builtins:

class int(object)
| int([x]) -> integer
| int(x, base=10) -> integer
|
| Convert a number or string to an integer, or return 0 if no arguments
| are given. If x is a number, return x.__int__(). For floating point
| numbers, this truncates towards zero.
|
| If x is not a number or if base is given, then x must be a string,
| bytes, or bytearray instance representing an integer literal in the
| given base. The literal can be preceded by ‘+’ or ‘-‘ and be surrounded
| by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.
| Base 0 means to interpret the base from the string as an integer literal.
| >>> int(‘0b100’, base=0)
| 4
|
| Methods defined here:
|
| __abs__(self, /)
| abs(self)
—More—

The following displays the docstring of the user-defined class.

class student: def __init__(self): '''The student class is initialized''' def print_student(self): '''Returns the student description''' print('student description') help(student) 
Help on class student in module __main__: class student(builtins.object) | Methods defined here: | | __init__(self) | The student class is initialized | | print_student(self) | Returns the student description | | ---------------------------------------------------------------------- | Data descriptors defined here: | | __dict__ | dictionary for instance variables (if defined) | | __weakref__ | list of weak references to the object (if defined) 

Источник

Функция help() в Python: вызов справки

Когда вам нужна помощь в написании программы, использовании модулей, а также для вызова справки рекомендуется использовать функцию help() в Python.

Руководство функции Python help()

Что такое help() в Python?

help() в Python — это встроенный метод, который используется для интерактивного использования. Функция help() используется для получения документации по указанному модулю, классу, функции, переменным и т.д.

Синтаксис

В справочной консоли мы можем указать имена модулей, классов и функций, чтобы получить их документацию.

Теперь перейдите в терминал или консоль CMD и введите следующую команду.

На данный момент версия Python3 является последней, поэтому введите python3, и вы увидите то, что показано ниже.

Теперь введите функцию help().

Теперь мы можем проверить следующие встроенные функции и модули.

Допустим, мы вводим коллекции, а затем получаем следующий вывод в консоли.

Параметры

Метод help() принимает максимум один параметр.

object передается в help()

Введите следующую команду.

Строка передается в качестве аргумента

Если строка передается в качестве аргумента, данная строка ищется как имя модуля, функции, класса, метода, ключевого слова или раздела документации, и печатается страница справки.

Если вы хотите выйти из справочной консоли, введите команду quit.

Определение help() для пользовательского класса и функций

Мы можем определить вывод функции help() для наших пользовательских классов и функций, указав docstring (строку документации).

По умолчанию в качестве строки документации используется первая строка комментария в теле метода. Его окружают три двойных кавычки.

Допустим, у нас есть файл python help_examples.py со следующим кодом.

Источник

Читайте также:  Android studio фрагменты kotlin
Оцените статью