How to get a function name as a string?

后端 未结 12 2077
后悔当初
后悔当初 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 04:56

    If you're interested in class methods too, Python 3.3+ has __qualname__ in addition to __name__.

    def my_function():
        pass
    
    class MyClass(object):
        def method(self):
            pass
    
    print(my_function.__name__)         # gives "my_function"
    print(MyClass.method.__name__)      # gives "method"
    
    print(my_function.__qualname__)     # gives "my_function"
    print(MyClass.method.__qualname__)  # gives "MyClass.method"
    

提交回复
热议问题