Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Python, how can you get the name of a member function's class?

I have a function that takes another function as a parameter. If the function is a member of a class, I need to find the name of that class. E.g.

def analyser(testFunc):
    print testFunc.__name__, 'belongs to the class, ...

I thought

testFunc.__class__ 

would solve my problems, but that just tells me that testFunc is a function.

like image 770
Charles Anderson Avatar asked Nov 20 '08 16:11

Charles Anderson


People also ask

How do I find the instance name of a Python?

Using attribute __name__ with type() , you can get the class name of an instance/object as shown in the example above.

How do you define a member of a class in Python?

A class in Python can be defined using the class keyword. As per the syntax above, a class is defined using the class keyword followed by the class name and : operator after the class name, which allows you to continue in the next indented line to define class members.

How do you print a class type in Python?

How to Print the Type of a Variable in Python. To get the type of a variable in Python, you can use the built-in type() function. In Python, everything is an object. So, when you use the type() function to print the type of the value stored in a variable to the console, it returns the class type of the object.

How do I get an instance of a class in Python?

There are two ways to access the instance variable of class:Within the class by using self and object reference. Using getattr() method.


2 Answers

From python 3.3, .im_class is gone. You can use .__qualname__ instead. Here is the corresponding PEP: https://www.python.org/dev/peps/pep-3155/

class C:
    def f(): pass
    class D:
        def g(): pass

print(C.__qualname__) # 'C'
print(C.f.__qualname__) # 'C.f'
print(C.D.__qualname__) #'C.D'
print(C.D.g.__qualname__) #'C.D.g'

With nested functions:

def f():
    def g():
        pass
    return g

f.__qualname__  # 'f'
f().__qualname__  # 'f.<locals>.g'
like image 100
Conchylicultor Avatar answered Oct 20 '22 19:10

Conchylicultor


testFunc.im_class

https://docs.python.org/reference/datamodel.html#the-standard-type-hierarchy

im_class is the class of im_self for bound methods or the class that asked for the method for unbound methods

like image 45
Piotr Lesnicki Avatar answered Oct 20 '22 18:10

Piotr Lesnicki