如何从 Python 中的被调用函数访问调用方法的 __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
implicit __class__
reference 仅当您在方法中实际引用它(或使用 super
)时才会在 compile-time 处创建。例如这段代码:
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'>}
要找到调用函数的 class(在大多数情况下),您可以将一些 CPython-specific inspect
咒语链接在一起:
- 找到调用函数:How to get current function into a variable?
- 找到该函数的 class:Get defining class of unbound method object in Python 3
我不推荐它。
此处 __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
implicit __class__
reference 仅当您在方法中实际引用它(或使用 super
)时才会在 compile-time 处创建。例如这段代码:
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'>}
要找到调用函数的 class(在大多数情况下),您可以将一些 CPython-specific inspect
咒语链接在一起:
- 找到调用函数:How to get current function into a variable?
- 找到该函数的 class:Get defining class of unbound method object in Python 3
我不推荐它。