El sistema de ayuda de Python

    Al escribir y ejecutar sus programas Python, es posible que se quede atascado y necesite ayuda. Es posible que necesite conocer el significado de ciertos módulos, clases, funciones, palabras clave, etc. La buena noticia es que Python viene con un sistema de ayuda incorporado. Esto significa que no tiene que buscar ayuda fuera de Python.

    En este artículo, aprenderá a utilizar el sistema de ayuda integrado de Python.

    Función de ayuda de Python ()

    Esta función nos ayuda a obtener la documentación de una determinada clase, función, variable, módulo, etc. La función debe usarse en la consola de Python para obtener detalles de varios objetos de Python.

    Pasar un objeto a la función help ()

    El python help() La función tiene la siguiente sintaxis:

    >>> help(object)
    

    En la sintaxis anterior, el object parámetro es el nombre del objeto sobre el que necesita obtener ayuda.

    Por ejemplo, para saber más sobre Python print función, escriba el siguiente comando en la consola de Python:

    >>> help(print)
    

    Salida:

    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.
    

    Para obtener ayuda para dict class, escriba lo siguiente en la consola de Python:

    Te puede interesar:Python para PNL: Creación del modelo TF-IDF desde cero
    >>> help(dict)
    

    Salida:

    Help on class dict in module builtins:
    
    class dict(object)
     |  dict() -> new empty dictionary
     |  dict(mapping) -> new dictionary initialized from a mapping object's
     |      (key, value) pairs
     |  dict(iterable) -> new dictionary initialized as if via:
     |      d = {}
     |      for k, v in iterable:
     |          d[k] = v
     |  dict(**kwargs) -> new dictionary initialized with the name=value pairs
     |      in the keyword argument list.  For example:  dict(one=1, two=2)
     |  
     |  Methods defined here:
     |  
     |  __contains__(self, key, /)
     |      True if D has a key k, else False.
     |  
     |  __delitem__(self, key, /)
     |      Delete self[key].
     |  
     |  __eq__(self, value, /)
     |      Return self==value.
     |  
     |  __ge__(self, value, /)
     |      Return self>=value.
     |  
    
    ...
    

    También puede pasar un objeto de lista real al help() función:

    >>> help(['a', 'b', 'c'])
    

    Salida:

    Help on list object:
    
    class list(object)
     |  list() -> new empty list
     |  list(iterable) -> new list initialized from iterable's items
     |  
     |  Methods defined here:
     |  
     |  __add__(self, value, /)
     |      Return self+value.
     |  
     |  __contains__(self, key, /)
     |      Return key in self.
     |  
     |  __delitem__(self, key, /)
     |      Delete self[key].
     |  
     |  __eq__(self, value, /)
     |      Return self==value.
     |  
     |  __ge__(self, value, /)
     |      Return self>=value.
     |  
     |  __getattribute__(self, name, /)
     |      Return getattr(self, name).
    
    ...
    

    Podemos ver que cuando pasa un objeto al help() función, se imprime su documentación o página de ayuda. En la siguiente sección, aprenderá a pasar argumentos de cadena a la help() función.

    Pasar un argumento de cadena para ayudar ()

    Si pasa una cadena como argumento, la cadena se tratará como el nombre de una función, módulo, palabra clave, método, clase o tema de documentación y se imprimirá la página de ayuda correspondiente. Para marcarlo como un argumento de cadena, enciérrelo entre comillas simples o dobles.

    Por ejemplo:

    >>> help('print')
    

    Salida:

    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.
    

    Aunque pasamos ‘imprimir’ como un argumento de cadena, todavía obtuvimos la documentación para Python print función. Aquí hay otro ejemplo:

    Te puede interesar:Python para PNL: Creación de un modelo de bolsa de palabras desde cero
    >>> help('def')
    

    Salida:

    Function definitions
    ********************
    
    A function definition defines a user-defined function object (see
    section *The standard type hierarchy*):
    
       funcdef        ::= [decorators] "def" funcname "(" [parameter_list] ")" ["->" expression] ":" suite
       decorators     ::= decorator+
       decorator      ::= "@" dotted_name ["(" [parameter_list [","]] ")"] NEWLINE
       dotted_name    ::= identifier ("." identifier)*
       parameter_list ::= (defparameter ",")*
                          | "*" [parameter] ("," defparameter)* ["," "**" parameter]
                          | "**" parameter
                          | defparameter [","] )
       parameter      ::= identifier [":" expression]
       defparameter   ::= parameter ["=" expression]
       funcname       ::= identifier
    
    A function definition is an executable statement.  Its execution binds
    the function name in the current local namespace to a function object
    (a wrapper around the executable code for the function).  This
    
    ...
    

    Aquí pasamos «def» como un argumento de cadena al help() function y devolvió la documentación para definir funciones.

    Si no se encuentra ningún objeto, método, función, clase o módulo que coincida, se le notificará. Por ejemplo:

    >>> help('qwerty')
    

    Salida:

    No Python documentation found for 'qwerty'.
    Use help() to get the interactive help utility.
    Use help(str) for help on the str class.
    

    Se nos notifica que no se encontró documentación para nuestra cadena.

    A veces, es posible que necesitemos ayuda sobre una determinada función que está definida en una determinada biblioteca de Python. Esto requiere que primero importemos la biblioteca. Un buen ejemplo es cuando necesitamos obtener la documentación para el log función definida en Python math biblioteca. En este caso, primero debemos importar el math biblioteca entonces llamamos a la help() funciona como se demuestra a continuación:

    >>> from math import log
    >>> help(log)
    

    Salida:

    Help on built-in function log in module math:
    
    log(...)
        log(x[, base])
        
        Return the logarithm of x to the given base.
        If the base not specified, returns the natural logarithm (base e) of x.
    

    Usar help () sin argumento

    los help() La función se puede utilizar sin un argumento. Si ejecuta la función sin un argumento, la utilidad de ayuda interactiva de Python se iniciará en la consola del intérprete. Solo tienes que escribir el siguiente comando en la consola de Python:

    Te puede interesar:Python para NLP: Embeddings de palabras para el aprendizaje profundo en Keras
    >>> help()
    

    Esto devolverá la utilidad de ayuda de Python en la que puede escribir el nombre del objeto sobre el que necesita obtener ayuda. Por ejemplo:

    help> print
    

    Salida:

    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.
    

    Para volver al mensaje anterior, simplemente presione «q».

    Aquí hay otro ejemplo:

    help> return
    

    Salida:

    The "return" statement
    **********************
    
       return_stmt ::= "return" [expression_list]
    
    "return" may only occur syntactically nested in a function definition,
    not within a nested class definition.
    
    If an expression list is present, it is evaluated, else "None" is
    substituted.
    
    "return" leaves the current function call with the expression list (or
    "None") as return value.
    
    When "return" passes control out of a "try" statement with a "finally"
    clause, that "finally" clause is executed before really leaving the
    function.
    
    In a generator function, the "return" statement indicates that the
    generator is done and will cause "StopIteration" to be raised. The
    returned value (if any) is used as an argument to construct
    "StopIteration" and becomes the "StopIteration.value" attribute.
    
    Related help topics: FUNCTIONS
    

    Para salir de la utilidad de ayuda y volver a la consola de Python, simplemente escriba «salir» y presione la tecla Intro:

    help> quit
    

    Salida:

    You are now leaving help and returning to the Python interpreter.
    If you want to ask for help on a particular object directly from the
    interpreter, you can type "help(object)".  Executing "help('string')"
    has the same effect as typing a particular string at the help> prompt.
    >>>
    

    En la siguiente sección, discutiremos cómo definir help() para nuestros objetos personalizados.

    Te puede interesar:Introducción al aprendizaje por refuerzo con Python

    Definición de documentos de ayuda para clases y funciones personalizadas

    Es posible para nosotros definir la salida de help() función para nuestras funciones y clases personalizadas mediante la definición de una cadena de documentos (cadena de documento). En Python, la primera cadena de comentarios agregada al cuerpo de un método se trata como su cadena de documentos. El comentario debe estar rodeado de tres comillas dobles. Por ejemplo:

    def product(a, b):
        """
        This function multiplies two given integers, a and b
        :param x: integer
        :param y: integer
        :returns: integer
        """
        return a * b
    

    En el ejemplo anterior, hemos definido una función llamada product. Esta función multiplica dos valores enteros, a y b se le pasa como argumentos / parámetros. Vea el comentario entre tres comillas dobles:

        """
        This function multiplies two given integers, a and b
        :param x: integer
        :param y: integer
        :returns: integer
        """
    

    Esto se tratará como la cadena de documentos de la función. product.

    Ahora, cree un nuevo archivo y asígnele el nombre «myfile.py». Agregue el siguiente código al archivo:

    def product(a, b):
        """
        This function multiplies two given integers, a and b
        :param x: integer
        :param y: integer
        :returns: integer
        """
        return a * b
    
    class Student:
        """
        Student class in Python. It will store student details
        """
        admission = 0
        name=""
    
        def __init__(self, adm, n):
            """
            A constructor of the student object
            :param adm: a positive integer,
            :param n: a string
            """
            self.admission = adm
            self.name = n
    

    En el ejemplo anterior, se ha definido una cadena de documentos para una función, clase y métodos.

    Ahora necesitamos demostrar cómo podemos obtener la cadena de documentos anterior como documentación de ayuda en nuestra consola de Python.

    Primero, necesitamos ejecutar el script en la consola para cargar tanto la función como la definición de clase en el entorno de Python. Podemos usar Python exec() método para esto. Ejecute el siguiente comando en la consola de Python:

    >>> exec(open("myfile.py").read())
    

    Alternativamente, si ha escrito el código dentro de Python IDLE, simplemente tiene que ejecutarlo.

    Te puede interesar:Redondear números en Python

    Ahora podemos confirmar si los módulos de función y clase se han detectado ejecutando el globals() comando en la consola de Python:

    >>> globals()
    

    En mi caso, obtengo el siguiente resultado:

    {'__doc__': None, 'log': <built-in function log>, '__builtins__': <module 'builtins' (built-in)>, '__spec__': None, '__package__': None, '__name__': '__main__', '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__file__': 'C:/Users/admin/myfile.py', 'Student': <class '__main__.Student', 'product': <function product at 0x0000000003569B70>}
    

    Como se muestra en la salida anterior, ambos Student y product están en el diccionario de alcance global. Ahora podemos usar el help() función para obtener ayuda para el Student clase y product función. Simplemente ejecute el siguiente comando en la consola de Python:

    >>> help('myfile')
    

    Salida:

    Help on module myfile:
    
    NAME
        myfile
    
    CLASSES
        builtins.object
            Student
        
        class Student(builtins.object)
         |  Student class in Python. It will store student details
         |  
         |  Methods defined here:
         |  
         |  __init__(self, adm, n)
         |      A constructor of the student object
         |      :param adm: a positive integer,
         |      :param n: a string
         |  
         |  ----------------------------------------------------------------------
         |  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:
         |  
         |  admission = 0
         |  
         |  name=""
    
    FUNCTIONS
        product(a, b)
            This function multiplies two given integers, a and b
            :param x: integer
            :param y: integer
            :returns: integer
    
    FILE
        c:usersadminmyfile.py
    

    Revisemos la documentación de ayuda para product función:

    >>> help('myfile.product')
    

    Salida:

    Help on function product in myfile:
    
    myfile.product = product(a, b)
        This function multiplies two given integers, a and b
        :param x: integer
        :param y: integer
        :returns: integer
    

    Ahora, accedamos a la documentación de ayuda para Student clase:

    >>> help('myfile.Student')
    

    Salida:

    Te puede interesar:Revisión del curso: Práctica de la visión por computadora con OpenCV y Python
    Help on class Student in myfile:
    
    myfile.Student = class Student(builtins.object)
     |  Student class in Python. It will store student details
     |  
     |  Methods defined here:
     |  
     |  __init__(self, adm, n)
     |      A constructor of the student object
     |      :param adm: a positive integer,
     |      :param n: a string
     |  
     |  ----------------------------------------------------------------------
     |  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:
     |  
     |  admission = 0
     |  
     |  name=""
     
    

    En la salida, podemos ver la documentación que escribimos para el Student clase.

    Conclusión

    Python viene con un sistema integrado del cual podemos obtener ayuda con respecto a módulos, clases, funciones y palabras clave. Se puede acceder a esta utilidad de ayuda mediante el uso de Python help() función en el REPL. Cuando llamamos a esta función y le pasamos un objeto, devuelve la página de ayuda o la documentación del objeto. Cuando ejecutamos la función sin un argumento, se abre la utilidad de ayuda donde podemos obtener ayuda sobre los objetos de forma interactiva. Finalmente, para obtener ayuda con respecto a nuestras clases y funciones personalizadas, podemos definir cadenas de documentos.

     

    Rate this post

    Etiquetas: