简体   繁体   English

如何从function截取实例化的class名称?

[英]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.

相关问题 如何为未实例化的对象实例化类函数? - How to instantiate a class function for not instantiated objects? 如何从另一个函数中截取一个函数中的变量 - How to intercept a variable in a function from another function Python mockito - 模拟从可测试函数实例化的类 - Python mockito - Mocking a class which is being instantiated from the testable function 如何拦截来自 Python 函数的多个警告? - How to intercept multiple warnings from a Python function? 我们能否找到从使用“ import as”导入的类实例化的对象的_local_类名? - Can we find the _local_ class-name of an object instantiated from a class imported with 'import as'? 在 class 定义中获取实例化变量名称 - Get instantiated variable name inside class definition 模拟已经实例化的python类的功能 - Mocking a function of an already instantiated python class 如何在statsmodels中将截距和系数与params函数分开 - How to separate the intercept and coefficient from params function in statsmodels 如何确定某个类是否被另一个类中的方法实例化? - How to determine if a class was instantiated by a method in another class? 如何使字符串转换为在全局函数内部实例化的变量名? - How do you make a string converted to a variable name instantiated inside of a function global?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM