How to intercept the instantiated class name from the function?

Question:

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?

Asked By: Marek

||

Answers:

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
Answered By: Corralien

You can access to the self attribute from f using the magic method self and access for the class and name, for example:

print(a.f.__self__.__class__.__name__)

So, your code will look like this:

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

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

a = A()
b = B()

print(f"{a.f.__self__.__class__.__name__}.{a.f.__name__}")
print(f"{b.f.__self__.__class__.__name__}.{b.f.__name__}")
print(f"{b.g.__self__.__class__.__name__}.{b.g.__name__}")
Answered By: Cristian Dominguez
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.