Reputation: 17152
assuming the simple case where Foo is
class Foo:
def some_func(self):
print('hellow world')
I only have access to the variable func where func is :
func = Foo.some_func
I am trying to get the Foo
class name from the variable func
func
Out[6]: <function __main__.Foo.some_func>
func.__class__.__name__
Out[7]: 'function'
I am expecting to get Foo
is there anyway to do that?
Upvotes: 2
Views: 780
Reputation: 2006
Python 3 solution:
def get_class_name(func):
return func.__qualname__.split('.')[0]
__qualname__
method actually prints Foo.some_func
for func
.
Splitting the string by .
and taking the first element, it should do the job.
Python 2 & 3 solution:
def get_class_name(func):
return func.__str__().split('.')[0].split()[-1]
Edit:
In Python 3, func.__str__()
prints <function Foo.some_func at 0x10c456b70>
.
In Python 2, func.__str__()
prints <unbound method Foo.some_func>
.
Upvotes: 4