如何在python中另一个类的函数中获取调用者类名? [英] How to get the caller class name inside a function of another class in python?
本文介绍了如何在python中另一个类的函数中获取调用者类名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的目标是模拟一个应用程序的序列图,我需要在运行时有关调用者和被调用者类名的信息.我可以成功检索调用者函数但无法获取调用者类名?
My objective is to stimulate a sequence diagram of an application for this I need the information about a caller and callee class names at runtime. I can successfully retrieve the caller function but not able to get a caller class name?
#Scenario caller.py:
import inspect
class A:
def Apple(self):
print "Hello"
b=B()
b.Bad()
class B:
def Bad(self):
print"dude"
print inspect.stack()
a=A()
a.Apple()
当我打印堆栈时,没有关于调用者类的信息.那么是否可以在运行时检索调用者类?
When I printed the stack there was no information about the caller class. So is it possible to retrieve the caller class during runtime ?
推荐答案
好吧,在对提示进行一些挖掘之后,我得到了:
Well, after some digging at the prompt, here's what I get:
stack = inspect.stack()
the_class = stack[1][0].f_locals["self"].__class__.__name__
the_method = stack[1][0].f_code.co_name
print("I was called by {}.{}()".format(the_class, the_method))
# => I was called by A.a()
调用时:
➤ python test.py
A.a()
B.b()
I was called by A.a()
给定文件 test.py
:
import inspect
class A:
def a(self):
print("A.a()")
B().b()
class B:
def b(self):
print("B.b()")
stack = inspect.stack()
the_class = stack[1][0].f_locals["self"].__class__.__name__
the_method = stack[1][0].f_code.co_name
print(" I was called by {}.{}()".format(the_class, the_method))
A().a()
不确定从对象以外的东西调用时它会如何表现.
Not sure how it will behave when called from something other than an object.
这篇关于如何在python中另一个类的函数中获取调用者类名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文