- Python help() method
- Need of the help() method
- Working of Python help() method
- Python help() function with a Class
- Python help() function with a function
- Python help() function with a module
- The help() function with a keyword
- Conclusion
- References
- Python help() function
- Python help() function
- Defining help() for custom class and functions
- Summary
- Функция help() в Python
- Определение help() для пользовательского класса и функций
- Вывод
Python help() method
Hey, folks! In this article, we will be focusing on a important explanatory function in Python — Python help() function.
Need of the help() method
While coding in a particular programming language, it is very essential for us to know the basic documentation of the framed language. This is when the help() function comes into picture.
This function provides us with the basic documentation of Python language. It gives us the information about the methods and instances associated with a particular method or class.
The help() method works with keywords, Classes, functions and modules to help us gain the basic terminologies, instances and working attached with it respectively.
Usually the help() method is used alongside the Python interpreter to gain access to the underlying details about Python objects passed to it as a parameter.
Working of Python help() method
As mentioned above, the help() method provides information about the Python objects passed to it.
If the help() function is mentioned without any parameter, it starts the interpreter console wherein we can mention any module, objects, class, etc to avail the documentation about the same.
Python help() function with a Class
The help function can be feeded with customized or pre-defined parameters to work with. We can create a customized class and pass it to the help() function to examine the documentation provided by the function.
class Info: lang = "Python" name = "JournalDev" obj = Info() help(Info)
We have created an user-defined class and passed it to the help() function. The help() function has returned the necessary documentation of the class ‘Info’.
Help on class Info in module __main__: class Info(builtins.object) | Data descriptors defined here: | | __dict__ | dictionary for instance variables (if defined) | | __weakref__ | list of weak references to the object (if defined) | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | lang = 'Python' | | name = 'JournalDev'
Python help() function with a function
The help() function helps us to access the syntax, parameter list and the description about any function passed to it using the below command.
Python help() function with a module
We can gain information about the module using the help() function. When a module is passed to the help() function, it provides the documentation in terms of the version, file location, contents of the module, and data associated with it.
The help() function with a keyword
On passing a Python keyword as parameter to the help() function, the function returns the documentation in terms of the class of the keyword, the methods associated with it, etc.
Conclusion
By this we have come to the end of this topic. We have understood the need and working of the help() function. I hope this concept is clear to all the readers.
Please feel free to comment, in case you happen to come across any doubt.
References
Python help() function
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
Python help() function is used to get the documentation of specified module, class, function, variables etc. This method is generally used with python interpreter console to get details about python objects.
Python help() function
If no argument is given, the interactive help system starts on the interpreter console. In python help console, we can specify module, class, function names to get their help documentation. Some of them are:
help> True help> collections help> builtins help> modules help> keywords help> symbols help> topics help> LOOPING
If you want to get out of help console, type quit . We can also get the help documentation directly from the python console by passing a parameter to help() function.
>>> help('collections') >>> help(print) >>> help(globals)
>>> help('builtins.globals') Help on built-in function globals in builtins: builtins.globals = globals() Return the dictionary containing the current scope's global variables. NOTE: Updates to this dictionary *will* affect name lookups in the current global scope and vice-versa.
Defining help() for custom class and functions
We can define help() function output for our custom classes and functions by defining docstring (documentation string). By default, the first comment string in the body of a method is used as its docstring. It’s surrounded by three double quotes. Let’s say we have a python file python_help_examples.py with following code.
def add(x, y): """ This function adds the given integer arguments :param x: integer :param y: integer :return: integer """ return x + y class Employee: """ Employee class, mapped to "employee" table in Database """ name = '' def __init__(self, i, n): """ Employee object constructor :param i: integer, must be positive :param n: string """ self.id = i self.name = n
Notice that we have defined docstring for function, class and its methods. You should follow some format for documentation, I have generated some part of them automatically using PyCharm IDE. NumPy docstring guide is a good place to get some idea around proper way of help documentation. Let’s see how to get this docstring as help documentation in python console. First of all, we will have to execute this script in the console to load our function and class definition. We can do this using exec() command.
>>> exec(open("python_help_examples.py").read())
>>> globals() , '__spec__': None, '__annotations__': <>, '__builtins__': , '__warningregistry__': , 'add': , 'Employee': >
Notice that ‘Employee’ and ‘add’ are present in the global scope dictionary. Now we can get the help documentation using help() function. Let’s look at some of the examples.
>>> help('python_help_examples.add') Help on function add in python_help_examples: python_help_examples.add = add(x, y) This function adds the given integer arguments :param x: integer :param y: integer :return: integer (END)
>>> help('python_help_examples.Employee')
>>> help('python_help_examples.Employee.__init__') Help on function __init__ in python_help_examples.Employee: python_help_examples.Employee.__init__ = __init__(self, i, n) Employee object constructor :param i: integer, must be positive :param n: string (END)
Summary
Python help() function is very helpful to get the details about modules, classes, and functions. It’s always best practice to define docstring for the custom classes and functions to explain their usage. You can checkout complete python script and more Python examples from our GitHub Repository. Reference: Official Documentation
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases. Learn more about us
Функция help() в Python
Функция help() в Python используется для получения документации по указанному модулю, классу, функции, переменным и т.д. Этот метод обычно используется с консолью интерпретатора Python для получения сведений об объектах.
Если аргумент не указан, интерактивная справочная система запускается на консоли интерпретатора.
В справочной консоли python мы можем указать имена модулей, классов и функций, чтобы получить справочную документацию. Некоторые из них:
help> True help> collections help> builtins help> modules help> keywords help> symbols help> topics help> LOOPING
Если вы хотите выйти из справочной консоли, введите quit.
Мы также можем получить справочную документацию прямо из консоли python, передав параметр в функцию help().
>>> help('collections') >>> help(print) >>> help(globals)
Посмотрим, что выводит функция help() для функции globals().
>>> help('builtins.globals') Help on built-in function globals in builtins: builtins.globals = globals() Return the dictionary containing the current scope's global variables. NOTE: Updates to this dictionary *will* affect name lookups in the current global scope and vice-versa.
Определение help() для пользовательского класса и функций
Мы можем определить вывод функции help() для наших пользовательских классов и функций, определив docstring (строку документации). По умолчанию первая строка комментария в теле метода используется в качестве его строки документации. Он окружен тремя двойными кавычками.
Допустим, у нас есть файл python python_help_examples.py со следующим кодом.
def add(x, y): """ This function adds the given integer arguments :param x: integer :param y: integer :return: integer """ return x + y class Employee: """ Employee class, mapped to "employee" table in Database """ name = '' def __init__(self, i, n): """ Employee object constructor :param i: integer, must be positive :param n: string """ self.id = i self.name = n
Обратите внимание, что мы определили строку документации для функции, класса и его методов. Вы должны следовать некоторому формату для документации, я сгенерировал часть из них автоматически с помощью PyCharm IDE.
Давайте посмотрим, как получить эту строку документации в качестве справочной документации в консоли Python.
Прежде всего, нам нужно выполнить этот скрипт в консоли, чтобы загрузить определение нашей функции и класса. Мы можем сделать это с помощью команды exec().
>>> exec(open("python_help_examples.py").read())
Мы можем проверить наличие функций и определений классов с помощью команды globals().
>>> globals() , '__spec__': None, '__annotations__': <>, '__builtins__': , '__warningregistry__': , 'add': , 'Employee': >
Обратите внимание, что «Employee» и «add» присутствуют в словаре глобальной области видимости.
Теперь мы можем получить справочную документацию с помощью функции help(). Давайте посмотрим на некоторые примеры.
>>> help('python_help_examples.add') Help on function add in python_help_examples: python_help_examples.add = add(x, y) This function adds the given integer arguments :param x: integer :param y: integer :return: integer (END)
>>> help('python_help_examples.Employee')
>>> help('python_help_examples.Employee.__init__') Help on function __init__ in python_help_examples.Employee: python_help_examples.Employee.__init__ = __init__(self, i, n) Employee object constructor :param i: integer, must be positive :param n: string (END)
Вывод
Функция help() в Python очень полезна для получения подробной информации о модулях, классах и функциях. Всегда рекомендуется определять строку документации для пользовательских классов и функций, чтобы объяснить их использование.