[python] - Commenting python code

4877 단어 pythonpython

Why commenting??

Documentation is a software engineering concept that provides the "explanation" of the code.

Documenting code is very important:

It helps communication between developers and is a great help when it comes to maintenance! Seeing code written by others is always nightmare.

  • The first style of comment uses the # character followed by the comment until the end of the line.
  • The second, more important style of comments, are called triple-quote comments or docstrings.

Function Docstrings

example 1 (Function)

def discuss(topic):
  """
  Discuss a topic with the user and return their response.
  Ask if the user likes the topic and why.
  
  Parameter:
    topic (str): The topic under discussion.
  
  Return:
    str: Response to the question of why they like the topic.
  """
  like = input("Do you like " + topic + "? ")
  response = input("Why do you think that? ")
  
  return response

example 2 (Class)

class Point(object) :
    """A 2D point ADT using Cartesian coordinates."""
    def __init__(self, x, y) :
        """Construct a point object based on (x, y) coordinates.
        Parameters:
            x (float): x coordinate in a 2D cartesian grid.
            y (float): y coordinate in a 2D cartesian grid.
    """
    self._x = x
    self._y = y
    def x(self) :
      """(float) Return the x coordinate of the point."""
      return self._x
    def y(self) :
        """(float) Return the y coordinate of the point."""
        return self._y
    def move(self, dx, dy) :
        """Move the point by (dx, dy).
        Parameters:
            dx (float): Amount to move in the x direction.
            dy (float): Amount to move in the y direction.
    """
        self._x += dx
        self._y += dy

🌟 Note that the comment for the init method does not have a Return: comment.

  • init method creates an object of the class type instead of returning a value

좋은 웹페이지 즐겨찾기