Python:如何从“框架"对象中检索类信息? [英] Python: How to retrieve class information from a 'frame' object?

查看:90
本文介绍了Python:如何从“框架"对象中检索类信息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以从框架对象中检索任何类信息?我知道如何获取文件(frame.f_code.co_filename),函数(frame.f_code.co_name)和行号(frame.f_lineno),但也希望能够获取活动对象的类的名称框架的实例(如果不在实例中,则为None).

Is it possible to retrieve any class information from a frame object? I know how to get the file (frame.f_code.co_filename), function (frame.f_code.co_name) and line number (frame.f_lineno), but would like to be able to also get the name of the class of the active object instance of the frame (or None if not in an instance).

推荐答案

我不认为在框架对象级别上,有任何方法可以找到已被调用的实际python函数对象.

I don't believe that, at the frame object level, there's any way to find the actual python function object that has been called.

但是,如果您的代码依赖于通用约定:命名方法self的实例参数,则可以执行以下操作:

However, if your code rely on the common convention : naming the instance parameter of a method self, then you could do the following :

def get_class_from_frame(fr):
  import inspect
  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

如果您不想使用 getargvalues ,您可以直接使用frame.f_locals代替value_dictframe.f_code.co_varnames[:frame.f_code.co_argcount]代替args.

If you don't want to use getargvalues, you can use directly frame.f_locals instead of value_dict and frame.f_code.co_varnames[:frame.f_code.co_argcount] instead of args.

请记住,这仍然仅依靠约定,因此它不是可移植的,并且容易出错:

Keep in mind that this is still only relying on convention, so it is not portable, and error-prone:

  • 如果非方法函数使用self作为第一个参数名称,则get_class_from_frame将错误地返回第一个参数的类.
  • 使用描述符时可能会产生误导(它将返回描述符的类,而不是所访问的实际实例的类).
  • @classmethod@staticmethod不会采用self参数,而是通过描述符实现的.
  • 当然还有很多
  • if a non-method function use self as first parameter name, then get_class_from_frame will wrongly return the class of the first parameter.
  • it can be misleading when working with descriptors (it will return the class of the descriptor, not of the actual instance being accessed).
  • @classmethod and @staticmethod won't take a self parameter and are implemented with descriptors.
  • and surely a lot more

根据您要执行的操作,您可能需要花一些时间来深入研究并找到所有这些问题的解决方法(您可以检查返回的类中是否存在frame函数并共享相同的源,检测描述符调用是可能的,与类方法等一样.)

Depending on what exactly you want to do, you might want to take some time to dig deeper and find workarounds for all these issues (you could check the frame function exist in the returned class and share the same source, detecting descriptor calls is possible, same for class methods, etc..)

这篇关于Python:如何从“框架"对象中检索类信息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆