[英]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我得到的 output
A.f
A.f
B.g
the output I am expecting我期待的 output
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.因为我关心的不仅是 function 名称,还有 class 名称,而不是真正定义 function 的 class,而是实例化的 class。 Anyone has an idea how to get it?任何人都知道如何获得它?
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
You can access to the self attribute from f using the magic method self and access for the class and name, for example:您可以使用魔术方法self访问 f 的 self 属性,并访问 class 和名称,例如:
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__}")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.