27

There seem to be two places where you can put docstrings for a class:

  1. Right under the class definition:

    class MyClass:
        """Summary of MyClass.
    
        Body.
        """
    
  2. Right under the __init__ constructor:

    class MyClass:
        def __init__(self, arg1, arg2):
            """Summary of MyClass.
    
            Body.
            """
    

Which is preferred? Or is it okay to have both?

Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
Jin
  • 778
  • 1
  • 8
  • 23

1 Answers1

31

They can both exist, since they are both intended for different things.

The docstring for a class should summarize its behavior and list the public methods and instance variables. If the class is intended to be subclassed, and has an additional interface for subclasses, this interface should be listed separately (in the docstring). The class constructor should be documented in the docstring for its __init__ method. Individual methods should be documented by their own docstring.

Emphasis mine. This reference is from PEP 257 -- Docstring Conventions

wim
  • 338,267
  • 99
  • 616
  • 750
  • 3
    Also, for sphinx documentation I found there is an option to show both [class and `__init__` docstring by setting `autoclass_content = both`](https://stackoverflow.com/questions/5599254/how-to-use-sphinxs-autodoc-to-document-a-classs-init-self-method) – Jin Jan 15 '19 at 19:00