繁体   English   中英

如何从Python中的callee函数访问调用方法的__class__属性?

[英]How to access a caller method's __class__ attribute from a callee function in Python?

这里__class__不应该与self.__class__混淆,我已经能够通过inspect模块访问它了:

import inspect


class A:

    def __init__(self):
        print(__class__.__name__)  # I want to move this statement inside f
        f()


class B(A):
    pass


def f():
    prev_frame = inspect.currentframe().f_back
    self = prev_frame.f_locals["self"]
    print(self.__class__.__name__)


B()  # prints A B

只有在方法中实际引用它(或使用super )时,才会在编译时创建隐式__class__引用 例如这段代码:

class Foo:
    def bar(self):
        print('bar', locals())

    def baz(self):
        print('baz', locals())

        if False:
            __class__

if __name__ == '__main__':
    foo = Foo()

    foo.bar()
    foo.baz()

生成此输出:

bar {'self': <__main__.Foo object at 0x10f45f978>}
baz {'self': <__main__.Foo object at 0x10f45f978>, '__class__': <class '__main__.Foo'>}

要查找调用函数的类(在大多数情况下),您可以将一些特定于CPython的inspect咒语链接在一起:

  1. 找到调用函数: 如何将当前函数转换为变量?
  2. 找到该函数的类: 在Python 3中获取未绑定方法对象的定义类

我不推荐它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM