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.
Using attribute __name__ with type() , you can get the class name of an instance/object as shown in the example above.
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 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.
There are two ways to access the instance variable of class:Within the class by using self and object reference. Using getattr() method.
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'
testFunc.im_class
https://docs.python.org/reference/datamodel.html#the-standard-type-hierarchy
im_class
is the class ofim_self
for bound methods or the class that asked for the method for unbound methods
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With