Search code examples
pythonoopinheritanceinstance

How to intercept the instantiated class name from the function?


I encountered an issue in one of my projects, I managed to reduce it to a simplest example possible. Consider the following

class A:
    def f(self):
        return 'I am f()'

class B(A):
    def g(self):
        return 'I am g()'

a = A()
b = B()

print(a.f.__qualname__)
print(b.f.__qualname__)
print(b.g.__qualname__)

The output I am getting

A.f
A.f
B.g

the output I am expecting

A.f
B.f
B.g

because what I care about is not only the function name, but also the class name, not really the class in which the function is defined but rather the class that gets instantiated. Anyone has an idea how to get it?


Solution

  • I think you can try something like:

    def dynamic_qualname(method):
        return method.__self__.__class__.__name__ + '.' + method.__name__
    
    print(dynamic_qualname(a.f))
    print(dynamic_qualname(b.f))
    print(dynamic_qualname(b.g))
    
    # Output
    A.f
    B.f
    B.g