python如何查看类信息_Python:如何从“框架”对象中检索类信息?

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

解决方案

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.

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

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:

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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值