Get a function name in Python

We can get a function name by the __name__ attribute.

def hello():
    return 'hello'

n = hello.__name__

print(n)  # hello


All are, in principle, objects in Python and a function itself is an object. It has several built-in methods like __class__ and __name__.

def hello():
    return 'hello'

a = isinstance(hello, object)

print(a)  # True

s = hello.__str__()
c = hello.__class__
n = hello.__name__

print(s)  # <function hello at 0x1037dc1f0>
print(c)  # <class 'function'>
print(n)  # hello

Note that isinstance is used to check the object type. __str__ returns an object type of the function. To get a function name, it's enough to use __name__.

Get the list of methods

class A:

    def __init__(self):

    def buy(self):

a = A()

x = a.__dir__()
y = A.__dict__.keys()

# ['__module__', '__init__', 'buy', '__dict__', '__weakref__', '__doc__', '__repr__', '__hash__', '__str__', '__getattribute__', '__setattr__', '__delattr__', '__lt__', '__le__', '__eq__', '__ne__', '__gt__', '__ge__', '__new__', '__reduce_ex__', '__reduce__', '__subclasshook__', '__init_subclass__', '__format__', '__sizeof__', '__dir__', '__class__']

# dict_keys(['__module__', '__init__', 'buy', '__dict__', '__weakref__', '__doc__'])

To get all the methods, use __dir__ or __dict__.

__dir__ is a method of instance and __dict__ is a method of class. Both results contain buy function.


Powered by Markdown