我的目标是为此激发应用程序的序列图我需要在运行时有关调用者和被调用者类名的信息。我可以成功检索调用者函数但无法获取调用者类名称吗?
#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()
当我打印堆栈时,没有关于调用者类的信息。那么可以在运行时检索调用者类吗?
答案 0 :(得分:31)
嗯,经过一些挖掘提示,这就是我得到的:
stack = inspect.stack()
the_class = stack[1][0].f_locals["self"].__class__
the_method = stack[1][0].f_code.co_name
print("I was called by {}.{}()".format(str(calling_class), calling_code_name))
# => I was called by A.a()
调用时:
➤ python test.py
A.a()
B.b()
I was called by __main__.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__
the_method = stack[1][0].f_code.co_name
print(" I was called by {}.{}()".format(str(the_class), the_method))
A().a()
不确定从对象以外的其他东西调用时的行为方式。
答案 1 :(得分:4)
使用Python: How to retrieve class information from a 'frame' object?
的答案我得到这样的东西......
import inspect
def get_class_from_frame(fr):
args, _, _, value_dict = inspect.getargvalues(fr)
# we check the first parameter for the frame function is
# named 'self'
if len(args) and args[0] == 'self':
# in that case, 'self' will be referenced in value_dict
instance = value_dict.get('self', None)
if instance:
# return its class
return getattr(instance, '__class__', None)
# return None otherwise
return None
class A(object):
def Apple(self):
print "Hello"
b=B()
b.Bad()
class B(object):
def Bad(self):
print"dude"
frame = inspect.stack()[1][0]
print get_class_from_frame(frame)
a=A()
a.Apple()
给出了以下输出:
Hello
dude
<class '__main__.A'>
显然这会返回对类本身的引用。如果您想要该类的名称,可以从__name__
属性中获取该名称。
不幸的是,这不适用于类或静态方法......
答案 2 :(得分:3)
也许这打破了一些Python编程协议,但如果Bad 总是要检查调用者的类,为什么不将调用者的__class__
作为调用的一部分传递给它?
class A:
def Apple(self):
print "Hello"
b=B()
b.Bad(self.__class__)
class B:
def Bad(self, cls):
print "dude"
print "Calling class:", cls
a=A()
a.Apple()
结果:
Hello
dude
Calling class: __main__.A
如果这是一个糟糕的形式,并且使用inspect
确实是获得调用者类的首选方法,请解释原因。我还在学习更深入的Python概念。
答案 3 :(得分:0)
将类实例名称从堆栈存储到类变量:
import inspect
class myClass():
caller = ""
def __init__(self):
s = str(inspect.stack()[1][4]).split()[0][2:]
self.caller = s
def getInstanceName(self):
return self.caller
此
myClassInstance1 = myClass()
print(myClassInstance1.getInstanceName())
将打印:
myClassInstance1
答案 4 :(得分:0)
可以使用inspect.currentframe()方法代替索引inspector.stack()的返回值,从而避免建立索引。
prev_frame = inspect.currentframe().f_back
the_class = prev_frame.f_locals["self"].__class__
the_method = prev_frame.f_code.co_name
答案 5 :(得分:0)
Python 3.8
import inspect
class B:
def __init__(self):
if (parent := inspect.stack()[1][0].f_locals.get('self', None)) and isinstance(parent, A):
parent.print_coin()
class A:
def __init__(self, coin):
self.coin: str = coin
B()
def print_coin(self):
print(f'Coin name: {self.coin}')
A('Bitcoin')