How to print Docstring of python function from inside the function itself?

后端 未结 8 1644
無奈伤痛
無奈伤痛 2020-12-04 23:26

I want to print the docstring of a python function from inside the function itself. for eg.

def my_function(self):
  \"\"\"Doc string for my function.\"\"\"
         


        
8条回答
  •  清歌不尽
    2020-12-05 00:02

    This works:

    def my_function():
      """Docstring for my function"""
      #print the Docstring here.
      print my_function.__doc__
    
    my_function()
    

    in Python 2.7.1

    This also works:

    class MyClass(object):
        def my_function(self):
            """Docstring for my function"""
            #print the Docstring here, either way works.
            print MyClass.my_function.__doc__
            print self.my_function.__doc__
    
    
    foo = MyClass()
    
    foo.my_function()
    

    This however, will not work on its own:

    class MyClass(object):
        def my_function(self):
            """Docstring for my function"""
            #print the Docstring here.
            print my_function.__doc__
    
    
    foo = MyClass()
    
    foo.my_function()
    

    NameError: global name 'my_function' is not defined

提交回复
热议问题