1

How do I print documentation strings within classes

For functions i can do this:

def func():  
    """
     doc string
    """


print func.__doc__

Is it possible to do the same thing with a class

class MyClass(object):

    def __init__(self):
        """
        doc string
        """

i = MyClass()  
print i.__doc__

This doesn't work. It only prints out None.
Am writing a text game and I want to use the doc string as an instruction to the player without using the print command

Thanks

2 Answers 2

10

It's None because the class does not have a docstring. Try adding one:

class MyClass(object):
    """ Documentation for MyClass goes here. """

    def __init__(self):
        """
        doc string
        """

i = MyClass()  
print i.__doc__ # same as MyClass.__doc__
Sign up to request clarification or add additional context in comments.

1 Comment

Ok. so the doc strings goes directly into the class and not inside the init func. Thank you
3

You defined a doc string for the method MyClass.__init__ not MyClass:

print i.__init__.__doc__

Put the doc string for the class after the class declaration:

class MyClass(object):
    ''' MyClass ... '''

And there is always:

help(i)

To get the class and method doc strings in a single document.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.