How to get a function name as a string?

后端 未结 12 2066
后悔当初
后悔当初 2020-11-22 04:35

In Python, how do I get a function name as a string, without calling the function?

def my_function():
    pass

print get_function_name_as_string(my_function         


        
12条回答
  •  别跟我提以往
    2020-11-22 05:11

    You just want to get the name of the function here is a simple code for that. let say you have these functions defined

    def function1():
        print "function1"
    
    def function2():
        print "function2"
    
    def function3():
        print "function3"
    print function1.__name__
    

    the output will be function1

    Now let say you have these functions in a list

    a = [function1 , function2 , funciton3]
    

    to get the name of the functions

    for i in a:
        print i.__name__
    

    the output will be

    function1
    function2
    function3

提交回复
热议问题