Reputation: 1257
The documentation string (docstring) is like a comment; but used in different way. It is used to give brief info of any class, function, method, module, etc. It is not mandatory but obligatory for source code.
Docstring give the code more readability and understanding. Print the documentation string (docstring) from module, function, class, or method definition.
class Test(object):
''' class documentation '''
var = 5
def __init__(self):
''' init(constructor) documentation '''
self.var = 9
def change(self):
''' change(self) '''
self.var = 13
print self.var
def __del__(self):
print "Destructor deleting object - ", self.var
cls = Test()
print Test.__doc__
print cls.__init__.__doc__
print cls.change.__doc__
print Test.var
print cls.var
cls.change()
def PrintDoc():
""" inside PrintDoc """
new = 12
print PrintDoc.__doc__
Upvotes: 2
Views: 5814
Reputation: 7529
You can print the module's docstring:
"""This module does things"""
if __name__ == '__main__':
print __doc__
Or just have a main
function:
def main():
"""What I do when ran as a script"""
pass
if __name__ == '__main__':
print main.__doc__
main()
Upvotes: 6
Reputation: 336128
So, in effect you want to print the docstring of the current module, right? A docstring needs to be the first string in the file. You can't put it after the if
statement as in your code sample - that isn't a docstring anymore.
But if it's at the top of the file, you can simply
print __doc__
Upvotes: 0