如何检查从哪个类方法派生的Python? [英] How to check in Python from which class methods is derived?

查看:86
本文介绍了如何检查从哪个类方法派生的Python?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两节课:

class A(object):
  def a(self):
    pass

class B(A):
  def b(self):
    pass

print dir(A)
print dir(B)

如何检查Python派生自哪些类方法?

How can I check from which class methods is derived in Python?

例如:

getMethodClass(A.a) == A
getMethodClass(B.a) == A
getMethodClass(B.b) == B

推荐答案

有趣的问题.这是我的处理方法.

Interesting question. Here is how I'd go about it.

(这在python2中有效.我尚未在python3中对其进行过测试,但是如果它不起作用,我也不会感到惊讶...)

您可以使用reversed(inspect.getmro(cls))遍历所有被提名人",并返回满足条件的第一个(通过获取迭代器的next值)满足条件的对象,该条件具有相关的attr与相关cls的方法相同.

You can iterate over all the "nominees" using reversed(inspect.getmro(cls)), and returning the first (by fetching the next value of the iterator) which satisfy the condition that it has the relevant attr, and that attr is the same as the method of the relevant cls.

方法身份比较是通过比较未绑定方法的im_func属性来完成的.

Method identity-comparison is done by comparing the im_func attribute of the unbound method.

import inspect

def getMethodClass(cls, attr):
   return next(
      basecls for basecls in reversed(inspect.getmro(cls))
      if hasattr(basecls, attr)
      and getattr(basecls, attr).im_func is getattr(cls, attr).im_func
   )

getMethodClass(A, 'a')
=> __main__.A
getMethodClass(B, 'a')
=> __main__.A
getMethodClass(B, 'b')
=> __main__.B

# an alternative implementation, suggested by @chameleon
def getAttributeClass(cls, attrName):
  # check first if has attribute
  attr = getattr(cls, attrName)

  mro = inspect.getmro(cls)
  # only one class on list
  if len(mro) == 1:
    return cls

  # many class on list
  for base in reversed(mro[1:]):
    # check if defined in this base
    try:
      baseAttr = getattr(base, attrName)
    except AttributeError:
      continue
    else:
      if baseAttr.im_func is attr.im_func:
        return base
  # define in top class
  return cls

该函数还可以具有您建议的签名:

The function can also have the signature you suggest:

def getMethodClass(unbound_method):
    cls = unbound_method.im_class
    attr = unbound_method.__name__
    # rest of implementation is the same as before...

getMethodClass(B.a)
=> __main__.A

这篇关于如何检查从哪个类方法派生的Python?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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