如何在python中获取另一个类的函数中的调用方类名?

2024-04-28 20:45:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我的目标是模拟一个应用程序的序列图,为此我需要在运行时获得关于调用者和被调用者类名的信息。我可以成功检索调用方函数,但无法获取调用方类名?

#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()

当我打印堆栈时,没有关于调用方类的信息。那么在运行时是否可以检索调用方类?


Tags: 函数self信息应用程序apple目标defclass
2条回答

使用来自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__属性中获取。

不幸的是,这不适用于类或静态方法。。。

好吧,在经过一番调查之后,我得到了如下结论:

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()

不确定当从对象以外的对象调用时它将如何工作。

相关问题 更多 >