1def my_function():
2 pass
3
4class MyClass(object):
5 def method(self):
6 pass
7
8print(my_function.__name__) # gives "my_function"
9print(MyClass.method.__name__) # gives "method"
10
11print(my_function.__qualname__) # gives "my_function"
12print(MyClass.method.__qualname__) # gives "MyClass.method"
1# You can get any function's or class's name as a string with __name__.
2# In fact, using just __name__ will return a module's name, or "__main__"
3# if the file is the current running script
4def this_is_my_name():
5 pass
6
7class MyName:
8 def __init__(self) -> None:
9 pass
10
11 def __str__(self) -> str:
12 # this is just so we can get a more readable output
13 return "MyName Object"
14
15# as you can see later on, you can't get a variable's name the same way
16named_variable = 231
17named_instance = MyName()
18
19list_of_stuff_w_names = [this_is_my_name, MyName, named_instance, named_variable]
20
21print ("- Script running in", __name__)
22
23for stuff_w_name in list_of_stuff_w_names:
24 try:
25 print ("-", f"{stuff_w_name.__name__ = }")
26 except AttributeError:
27 print ("-", stuff_w_name, "doesn't have a __name__!")
28
29"""
30OUTPUT:
31- Script running in __main__
32- stuff_w_name.__name__ = 'this_is_my_name'
33- stuff_w_name.__name__ = 'MyName'
34- MyName Object doesn't have a __name__!
35- 231 doesn't have a __name__!
36"""